template
The template middleware provides HTML rendering using Go template for Flame instances.
You can read source code of this middleware on GitHub and API documentation on pkg.go.dev.
Installation
go get github.com/flamego/templateUsage examples
html/template package for syntax and constraints.The template.Templater works out-of-the-box with an optional template.Options.
By default, the templates files should resides in the “templates” directory and has extension of either .html or .tmpl. The special data type template.Data is provided as container to store any data you would want to be used in rendering the template.
Using local files
package main
import (
"net/http"
"github.com/flamego/flamego"
"github.com/flamego/template"
)
func main() {
f := flamego.Classic()
f.Use(template.Templater())
type Book struct {
Name string
Author string
}
f.Get("/", func(t template.Template, data template.Data) {
data["Name"] = "Joe"
data["Books"] = []*Book{
{
Name: "Designing Data-Intensive Applications",
Author: "Martin Kleppmann",
},
{
Name: "Shape Up",
Author: "Basecamp",
},
}
t.HTML(http.StatusOK, "home")
})
f.Run()
}Using the embed.FS
The template.EmbedFS is a handy helper to convert your embed.FS into the template.FileSystem.
$ tree .
.
├── templates
│ ├── embed.go
│ ├── home.tmpl
├── go.mod
├── go.sum
└── main.goTemplate caching
When your application is running with flamego.EnvTypeDev (default) or flamego.EnvTypeTest, template files are reloaded and recomplied upon every client request.
Set the Env to flamego.EnvTypeProd to enable template caching in production.