Back to godoc.org
github.com/apisite/tpl2x/gin-tpl2x

Package gintpl2x

v0.2.2
Latest Go to latest

The latest major version is .

Published: Apr 1, 2019 | License: MIT | Module: github.com/apisite/tpl2x/gin-tpl2x

Overview

Package gintpl2x implements a gin frontend for tpl2x.

Example

Code:

package main

import (
	"fmt"
	"html/template"
	"net/http"
	"net/http/httptest"

	mapper "github.com/birkirb/loggers-mapper-logrus"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"github.com/apisite/tpl2x"
	"github.com/apisite/tpl2x/gin-tpl2x"
	"github.com/apisite/tpl2x/lookupfs"

	"github.com/apisite/tpl2x/gin-tpl2x/samplefs"
	"github.com/apisite/tpl2x/gin-tpl2x/samplemeta"
)

func main() {

	// BufferPool size for rendered templates
	const bufferSize int = 64

	l := logrus.New()
	log := mapper.NewLogger(l)

	allFuncs := make(template.FuncMap)
	setProtoFuncs(allFuncs)

	cfg := lookupfs.Config{
		Includes:   "inc",
		Layouts:    "layout",
		Pages:      "page",
		Ext:        ".tmpl",
		DefLayout:  "default",
		Index:      "index",
		HidePrefix: ".",
	}
	// Here we attach an embedded filesystem
	fs := lookupfs.New(cfg).FileSystem(samplefs.FS())
	// Parse all of templates
	tfs, err := tpl2x.New(bufferSize).Funcs(allFuncs).LookupFS(fs).Parse()
	if err != nil {
		log.Fatal(err)
	}
	gintpl := gintpl2x.New(log, tfs)
	gintpl.RequestHandler = func(ctx *gin.Context, funcs template.FuncMap) gintpl2x.MetaData {
		setRequestFuncs(funcs, ctx)
		page := samplemeta.NewMeta(http.StatusOK, "text/html; charset=utf-8")
		return page
	}

	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	gintpl.Route("", r)

	req, _ := http.NewRequest("GET", "/", nil)
	resp := httptest.NewRecorder()

	r.ServeHTTP(resp, req)

	fmt.Println(resp.Code)
	fmt.Println(resp.Header().Get("Content-Type"))
	fmt.Println(resp.Body.String())

}

// setProtoFuncs appends function templates and not related to request functions to funcs
func setProtoFuncs(funcs template.FuncMap) {
	funcs["data"] = func() interface{} { return nil }
	funcs["request"] = func() interface{} { return nil }
	funcs["param"] = func(key string) string { return "" }
	funcs["HTML"] = func(s string) template.HTML {
		return template.HTML(s)
	}
}

// setRequestFuncs appends funcs which return real data inside request processing
func setRequestFuncs(funcs template.FuncMap, ctx *gin.Context) {
	funcs["data"] = func() interface{} { return samplemeta.Data }
	funcs["request"] = func() interface{} { return ctx.Request }
	funcs["param"] = func(key string) string { return ctx.Param(key) }
}
200
text/html; charset=utf-8
<html>
<head>
  <title>index page</title>
</head>
<body>
  <h2>Test data</h2>
<h3>My TODO list</h3>
<ul>
<li>Task 1
<li>Task 2
<li>Task 3
</ul>
<footer>
<hr>
Host: <br />
URL: /<br />
</footer>
</body>
</html>

Index

Examples

Constants

const EngineKey = "github.com/apisite/tpl2x"

EngineKey holds gin context key name for engine storage

type MetaData

type MetaData interface {
	tpl2x.MetaData
	ContentType() string // Returns content type
	Location() string    // Returns redirect url
	Status() int         // Response status
}

MetaData holds template metadata access methods

type Template

type Template struct {
	RequestHandler func(ctx *gin.Context, funcs template.FuncMap) MetaData
	// contains filtered or unexported fields
}

Template holds template engine attributes

func New

func New(log loggers.Contextual, fs TemplateService) *Template

New creates template object

func (Template) HTML

func (tmpl Template) HTML(ctx *gin.Context, uri string)

HTML renders page for given uri with context

func (*Template) Middleware

func (tmpl *Template) Middleware() gin.HandlerFunc

Middleware stores Engine in gin context

func (Template) Route

func (tmpl Template) Route(prefix string, r *gin.Engine)

Route registers template routes into gin

type TemplateService

type TemplateService interface {
	PageNames(hide bool) []string
	Render(w io.Writer, funcs template.FuncMap, data tpl2x.MetaData, content *bytes.Buffer) (err error)
	RenderContent(name string, funcs template.FuncMap, data tpl2x.MetaData) *bytes.Buffer
}

TemplateService allows to replace tpl2x functionality with the other package

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier