ginapitpl

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2019 License: MIT Imports: 7 Imported by: 1

Documentation

Overview

Package ginapitpl implements a gin frontend for apitpl.

Example
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/apitpl"
	"github.com/apisite/apitpl/ginapitpl"
	"github.com/apisite/apitpl/lookupfs"

	"github.com/apisite/apitpl/ginapitpl/samplefs"
	"github.com/apisite/apitpl/ginapitpl/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 := apitpl.New(bufferSize).Funcs(allFuncs).LookupFS(fs).Parse()
	if err != nil {
		log.Fatal(err)
	}
	gintpl := ginapitpl.New(log, tfs)
	gintpl.RequestHandler = func(ctx *gin.Context, funcs template.FuncMap) ginapitpl.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) }
}
Output:

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

View Source
const EngineKey = "github.com/apisite/apitpl"

EngineKey holds gin context key name for engine storage

Variables

This section is empty.

Functions

This section is empty.

Types

type MetaData

type MetaData interface {
	apitpl.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 apitpl.MetaData, content *bytes.Buffer) (err error)
	RenderContent(name string, funcs template.FuncMap, data apitpl.MetaData) *bytes.Buffer
}

TemplateService allows to replace apitpl functionality with the other package

Directories

Path Synopsis
Package samplefs contains embedded resources Package samplefs implements a sample embedded template filesystem for tests and examples for apitpl.
Package samplefs contains embedded resources Package samplefs implements a sample embedded template filesystem for tests and examples for apitpl.
Package samplemeta implements sample type Meta which holds template metadata
Package samplemeta implements sample type Meta which holds template metadata

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL