Documentation
¶
Overview ¶
Package apitpl implements template engine which renders templates by executing them 2 times, one for content and another one for layout.
Example (Execute) ¶
Render template with layout
package main
import (
"bytes"
"embed"
"html/template"
"io/fs"
"log"
"os"
"github.com/apisite/apitpl"
"github.com/apisite/apitpl/lookupfs"
"github.com/apisite/apitpl/samplemeta"
)
//go:embed testdata/*
var embedFS embed.FS
// Render template with layout
func main() {
// BufferPool size for rendered templates
const bufferSize int = 64
cfg := lookupfs.Config{
Includes: "inc_minimal",
Layouts: "layouts",
Pages: "pages",
Ext: ".html",
DefLayout: "default",
}
embedDirFS, _ := fs.Sub(embedFS, "testdata")
tfs, err := apitpl.New(bufferSize).
LookupFS(lookupfs.New(cfg).
FileSystem(embedDirFS)).
Parse()
if err != nil {
log.Fatal(err)
}
var b bytes.Buffer
page := &samplemeta.Meta{}
page.SetLayout("default")
err = tfs.Execute(&b, "subdir3/page", template.FuncMap{}, page)
if err != nil {
log.Fatal(err)
}
_, err = b.WriteTo(os.Stdout)
if err != nil {
log.Fatal(err)
}
}
Output: <title>Template title</title> == page2 here (inc2 here)==inc1
Example (Http) ¶
Handle set of templates via http
package main
import (
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
"net/http/httptest"
"github.com/apisite/apitpl"
"github.com/apisite/apitpl/lookupfs"
// samplefs "github.com/apisite/apitpl/testdata"
"github.com/apisite/apitpl/samplemeta"
)
// Handle set of templates via http
func main() {
// BufferPool size for rendered templates
const bufferSize int = 64
cfg := lookupfs.Config{
Includes: "includes",
Layouts: "layouts",
Pages: "pages",
Ext: ".html",
DefLayout: "default",
}
funcs := template.FuncMap{
"request": func() http.Request {
return http.Request{}
},
"content": func() template.HTML { return template.HTML("") },
}
embedDirFS, _ := fs.Sub(embedFS, "testdata")
tfs, err := apitpl.New(bufferSize).
Funcs(funcs).
LookupFS(
lookupfs.New(cfg).
FileSystem(embedDirFS)).
ParseAlways(true).
Parse()
if err != nil {
log.Fatal(err)
}
router := http.NewServeMux()
for _, uri := range tfs.PageNames(false) {
router.HandleFunc("/"+uri, handleHTML(tfs, uri))
}
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/subdir3/page", nil)
if err != nil {
log.Fatal(err)
}
router.ServeHTTP(resp, req)
fmt.Println(resp.Code)
fmt.Println(resp.Header().Get("Content-Type"))
fmt.Println(resp.Body.String())
}
// handleHTML returns page handler
func handleHTML(tfs *apitpl.TemplateService, uri string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// log.Debugf("Handling page (%s)", uri)
page := samplemeta.NewMeta(http.StatusOK, "text/html; charset=utf-8")
funcs := template.FuncMap{
"request": func() http.Request {
return *r
},
}
content := tfs.RenderContent(uri, funcs, page)
if page.Status() == http.StatusMovedPermanently || page.Status() == http.StatusFound {
http.Redirect(w, r, page.Title, page.Status())
return
}
header := w.Header()
header["Content-Type"] = []string{page.ContentType()}
w.WriteHeader(page.Status())
funcs["content"] = func() template.HTML { return template.HTML(content.Bytes()) }
err := tfs.Render(w, funcs, page, content)
if err != nil {
log.Fatal(err)
}
}
}
Output: 200 text/html; charset=utf-8 <title>Template title</title> == page2 here (inc2 here)==inc1 (URI: /subdir3/page)
Index ¶
- type MetaData
- type TemplateService
- func (tfs TemplateService) Execute(wr io.Writer, name string, funcs template.FuncMap, data MetaData) error
- func (tfs *TemplateService) Funcs(funcMap template.FuncMap) *TemplateService
- func (tfs *TemplateService) LookupFS(fs *lookupfs.LookupFileSystem) *TemplateService
- func (tfs TemplateService) PageNames(hide bool) []string
- func (tfs *TemplateService) Parse() (*TemplateService, error)
- func (tfs *TemplateService) ParseAlways(flag bool) *TemplateService
- func (tfs TemplateService) Render(w io.Writer, funcs template.FuncMap, data MetaData, content *bytes.Buffer) (err error)
- func (tfs TemplateService) RenderContent(name string, funcs template.FuncMap, data MetaData) *bytes.Buffer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type MetaData ¶
type MetaData interface {
Error() error // Template exec error
SetError(error) // Store unhandler template error
Layout() string // Return layout name
}
MetaData holds template metadata access methods
type TemplateService ¶
type TemplateService struct {
// contains filtered or unexported fields
}
TemplateService holds templates data & methods
func New ¶
func New(size int) (tfs *TemplateService)
New creates TemplateService with BufferPool of given size
func (TemplateService) Execute ¶
func (tfs TemplateService) Execute(wr io.Writer, name string, funcs template.FuncMap, data MetaData) error
Execute renders page content and layout
func (*TemplateService) Funcs ¶
func (tfs *TemplateService) Funcs(funcMap template.FuncMap) *TemplateService
Funcs loads initial funcmap
func (*TemplateService) LookupFS ¶
func (tfs *TemplateService) LookupFS(fs *lookupfs.LookupFileSystem) *TemplateService
LookupFS sets lookup filesystem
func (TemplateService) PageNames ¶
func (tfs TemplateService) PageNames(hide bool) []string
PageNames returns page names for router setup
func (*TemplateService) Parse ¶
func (tfs *TemplateService) Parse() (*TemplateService, error)
Parse parses all of service templates
func (*TemplateService) ParseAlways ¶
func (tfs *TemplateService) ParseAlways(flag bool) *TemplateService
ParseAlways disables template caching
func (TemplateService) Render ¶
func (tfs TemplateService) Render(w io.Writer, funcs template.FuncMap, data MetaData, content *bytes.Buffer) (err error)
Render renders layout with prepared content
func (TemplateService) RenderContent ¶
func (tfs TemplateService) RenderContent(name string, funcs template.FuncMap, data MetaData) *bytes.Buffer
RenderContent renders page content
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ginapitpl implements a gin frontend for apitpl.
|
Package ginapitpl implements a gin frontend for apitpl. |
|
samplemeta
Package samplemeta implements sample type Meta which holds template metadata
|
Package samplemeta implements sample type Meta which holds template metadata |
|
Package lookupfs implements a filesystem backend for apitpl.
|
Package lookupfs implements a filesystem backend for apitpl. |
|
Package samplemeta implements sample type Meta which holds template metadata
|
Package samplemeta implements sample type Meta which holds template metadata |
