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
- Host: GitHub
- URL: https://github.com/bluekeyes/templatetree
- Owner: bluekeyes
- License: mit
- Created: 2018-07-14T22:54:07.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2022-11-08T07:08:12.000Z (over 2 years ago)
- Last Synced: 2025-01-13T21:33:02.965Z (5 months ago)
- Topics: golang, inheritance, templates
- Language: Go
- Size: 31.3 KB
- Stars: 1
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# templatetree [](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 mainimport (
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.