tempest
Made out of neccessity and frustration π©
Features
- Use go templates in your app without repeating the parsing logic over and over.
- Use any template supported by go html/template package.
- Use
go:embed
to embed template files in your binary.
- Parse templates once.
Usage
In order for tempest to parse templates, three conditions must be met.
- Templates must be embeded
- The name of the template used for layouts should be
layouts.<extention>
, otherwise, it should be stated with custom config.
- The name of the folder containing partial templates should be "inludes", otherwise, it should be stated with custom config
π For requirements 2 and 3, see examples/with-conf
Requirements
Example
Lets say you have a folder structure like this
.
βββ main.go
βββ templates
Β Β βββ includes
Β Β βΒ Β βββ footer.html
Β Β | βββ header.html
Β Β βββ admin
Β Β β βββ dash.html
β βββ layout.html
Β Β βββ layout.html
βββ index.html
βββ about.html
In your main.go file, you can do something like this
package main
import (
"embed"
"log"
"github.com/noelukwa/tempest"
)
var (
//go:embed templates
templates embed.FS
)
func main() {
// Create a new tempest instance
tempst := tempest.New()
templs, err := tempst.ParseFS(templates)
if err != nil {
log.Fatal(err)
}
// Render a template
mux := http.NewServeMux()
mux.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
// π¨ Note that the template name is the file name without the extension
// and the base folder ; in this case "templates"
dash := templs["admin/dash"]
dash.Execute(w, nil)
})
}
Template Directory Parsing
The template files in the templates
directory above will be grouped as follows
- templates/admin/dash.html
βββ templates/layout.html
βββ templates/admin/layout.html
βββ templates/admin/dash.html
βββ templates/includes/footer.html
βββ templates/includes/header.html
- templates/index.html
βββ templates/layout.html
βββ templates/index.html
βββ templates/includes/footer.html
βββ templates/includes/header.html
- templates/about.html
βββ templates/layout.html
βββ templates/about.html
βββ templates/includes/footer.html
βββ templates/includes/header.html
html/template basics
When using nested layouts, the child layout's define
block name should correspond to the parent layout's block
name.
<!-- templates/layout.html -->
<main>
{{ block "content" . }}{{ end }}
</main>
<!-- templates/admin/layout.html -->
{{ define "content" }}
<section>
{{ block "admin-content" . }}{{ end }}
</section>
{{ end }}
Further Read: Go html/template package