跳到内容
template

template

template 中间件为 Flame 实例提供基于 Go 模板引擎的 HTML 渲染服务。

你可以在 GitHub 上阅读该中间件的源码或通过 pkg.go.dev 查看 API 文档。

下载安装

go get github.com/flamego/template

用法示例

本小结仅展示 template 中间件的相关用法,如需了解模板引擎的用法请移步 html/template 的文档。

template.Templater 可以配合 template.Options 对中间件进行配置。

默认情况下,模板文件都需要被存放在 “templates” 目录内,并以 .html.tmpl 作为文件名后缀。template.Data 是用于渲染模板的数据容器,即根对象。

使用本地文件

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()
}

使用 embed.FS

template.EmbedFS 是用于将 embed.FS 转换为 template.FileSystem 的辅助函数。

$ tree .
.
├── templates
│   ├── embed.go
│   ├── home.tmpl
├── go.mod
├── go.sum
└── main.go

模板缓存

当你的应用运行环境为 flamego.EnvTypeDev(默认运行环境)或 flamego.EnvTypeTest 时,每次响应客户端的请求都会对模板文件进行重新构建,便于开发调试。

通过 Env 函数将运行环境设置为 flamego.EnvTypeProd 可以启用模板缓存功能。