An open API service indexing awesome lists of open source software.

https://github.com/bluekeyes/templatetree

Simple template inheritance with standard Go templates
https://github.com/bluekeyes/templatetree

golang inheritance templates

Last synced: 3 months ago
JSON representation

Simple template inheritance with standard Go templates

Awesome Lists containing this project

README

        

# templatetree [![Go Reference](https://pkg.go.dev/badge/github.com/bluekeyes/templatetree.svg)](https://pkg.go.dev/github.com/bluekeyes/templatetree)

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**



{{block "title" .}}{{end}}


{{block "body" .}}{{end}}

**templates/index.html.tmpl**

{{/* templatetree:extends page.html.tmpl */}}
{{define "title"}}{{.Animal}} Status{{end}}
{{define "body"}}

The time is {{now}}


The {{.Animal}} is {{.Status}}


{{end}}

Use `Parse` to load and render the templates:

```go
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:



Walrus Status


The time is 2018-07-14T21:45:21.230-07:00


The Walrus is Forlorn



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.