templatetree

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2022 License: MIT Imports: 9 Imported by: 1

README

templatetree Go Reference

templatetree is a standard library template loader that creates simple template inheritance trees. Base templates use the block or template directives to define sections that are overridden or provided by child templates.

Compatible with both text/template and html/template.

Example

Given a templates directory with the following content:

templates/page.html.tmpl

<html>
  <head>
    <title>{{block "title" .}}{{end}}</title>
  </head>
  <body>
  {{block "body" .}}{{end}}
  </body>
</html>

templates/index.html.tmpl

{{/* templatetree:extends page.html.tmpl */}}
{{define "title"}}{{.Animal}} Status{{end}}
{{define "body"}}
  <p>The time is {{now}}</p>
  <p>The {{.Animal}} is {{.Status}}</p>
{{end}}

Use Parse to load and render the templates:

package main

import (
	html "html/template"
	"os"
	"time"

	"github.com/bluekeyes/templatetree"
)

func main() {
	factory := func(name string) templatetree.Template[*html.Template] {
		return template.New(name).Funcs(template.FuncMap{
			"now": func() string {
				return time.Now().Format(time.RFC3339)
			},
		})
	}

	t, err := templatetree.Parse("templates", "*.html.tmpl", factory)
	if err != nil {
		panic(err)
	}

	var data struct {
		Animal string
		Status string
	}
	data.Animal = "Walrus"
	data.Status = "Forlorn"

	if err := t.ExecuteTemplate(os.Stdout, "index.html.tmpl", &data); err != nil {
		panic(err)
	}
}

Output:

<html>
  <head>
    <title>Walrus Status</title>
  </head>
  <body>
    <p>The time is 2018-07-14T21:45:21.230-07:00</p>
    <p>The Walrus is Forlorn</p>
  </body>
</html>

You can also load templates from a fs.FS using templatetree.ParseFS or from memory using templatetree.ParseFiles. See the package documentation for details and an example.

Stability

Beta, API changes possible. v0.4.0 redesigned and simplified the API based on experience with previous versions. v0.5.0 inclued another API break to use generics, but is functionally the same as the previous version.

Documentation

Overview

Package templatetree loads standard library templates in a way that creates a template hierarchy with inheritance. Templates extend other templates by placing a special comment as the first line of the template. Template trees may be arbitrarily deep and multiple independent tree can be loaded at the same time.

The comment marking extension must be the first line of the template and must exactly match the following, including whitespace:

{{/* templatetree:extends parent-template-name */}}

If loading from a file system, a template's name is its slash-separated file path relative to the root. If parsing a map of files, the key sets the template's name.

To define functions or set other options on the templates, provide a custom factory function.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/bluekeyes/templatetree"
)

func main() {
	files := map[string]string{
		"base.tmpl": strings.TrimSpace(`
Header
{{block "body" .}}Body{{end}}
Footer
`),
		"a.tmpl": strings.TrimSpace(`
{{/* templatetree:extends base.tmpl */}}
{{define "body"}}Body A{{end}}
`),
		"b.tmpl": strings.TrimSpace(`
{{/* templatetree:extends base.tmpl */}}
{{define "body"}}Body B{{end}}
`),
	}

	t, err := templatetree.ParseFiles(files, templatetree.DefaultTextFactory)
	if err != nil {
		panic(err)
	}

	fmt.Println("--- a.tmpl ---")
	t.ExecuteTemplate(os.Stdout, "a.tmpl", nil)
	fmt.Println()

	fmt.Println("--- b.tmpl ---")
	t.ExecuteTemplate(os.Stdout, "b.tmpl", nil)
	fmt.Println()

}
Output:

--- a.tmpl ---
Header
Body A
Footer
--- b.tmpl ---
Header
Body B
Footer

Index

Examples

Constants

View Source
const (
	// CommentTagExtends is the tag used in template comments to mark a
	// template's parent.
	CommentTagExtends = "templatetree:extends"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type StdTemplate added in v0.5.0

type StdTemplate interface {
	*text.Template | *html.Template
}

StdTemplate is a union of the standard library template types.

type Template added in v0.4.0

type Template[T StdTemplate] interface {
	Name() string
	Execute(w io.Writer, data any) error
	ExecuteTemplate(w io.Writer, name string, data any) error
	Parse(text string) (T, error)
}

Template contains the common functions of text/template.Template and html/template.Template used by this package.

func DefaultHTMLFactory added in v0.5.0

func DefaultHTMLFactory(name string) Template[*html.Template]

DefaultHTMLFactory uses html/template.New to create templates.

func DefaultTextFactory added in v0.5.0

func DefaultTextFactory(name string) Template[*text.Template]

DefaultTextFactory uses text/template.New to create templates.

type TemplateFactory added in v0.4.0

type TemplateFactory[T StdTemplate] func(name string) Template[T]

TemplateFactory creates new empty templates.

type Tree added in v0.4.0

type Tree[T StdTemplate] map[string]Template[T]

Tree is a hierarchy of templates, mapping name to template. The concrete type of the values will be T.

func Parse added in v0.4.0

func Parse[T StdTemplate](dir, pattern string, f TemplateFactory[T]) (Tree[T], error)

Parse recursively loads all templates in dir with names matching pattern, respecting inheritance. Templates are named by their paths relative to dir.

func ParseFS added in v0.4.0

func ParseFS[T StdTemplate](fsys fs.FS, pattern string, f TemplateFactory[T]) (Tree[T], error)

ParseFS recursively parses all templates in fsys with names matching pattern, respecting inheritance. Templates are named by their paths in fsys.

func ParseFiles added in v0.4.0

func ParseFiles[T StdTemplate](files map[string]string, f TemplateFactory[T]) (Tree[T], error)

ParseFiles parses all templates in files, respecting inheritance. Templates are named by their key in files, which maps name to content.

func (Tree[T]) ExecuteTemplate added in v0.4.0

func (tree Tree[T]) ExecuteTemplate(wr io.Writer, name string, data any) error

ExecuteTemplate renders the template with the given name. See the text/template package for more details.

Jump to

Keyboard shortcuts

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