在公司构建用户个人站点的过程中使用使用到了模版
template
,在此总结一下
一、为什么要使用静态页面
页面应用对于在站点SEO方面存在局限性,而用户又希望可以通过SEO来增加网站的权重,所以使用了静态页面
二、解析过程
用到的函数
func (t *Template) New(name string) *Template
用给定的名称name创建一个template,这个name在后面的ParseFiles
里必须存在,不然会保存panic: template: "example" is an incomplete or empty template
func (t *Template) ParseFiles(filenames ...string) (*Template, error)
参数为一个或多个文件名,默认把一个文件作为主模版
func (t *Template) Execute(wr io.Writer, data interface{}) error
将给的数据应用到解析的模版上,如果报错,将停止执行,与ExecuteTemplate
的区别在于, ExecuteTemplate
可以通过第二个参数指定主模版
func (t *Template) Funcs(funcMap FuncMap) *Template
在模版中有时需要获取data中没有的数据、或者要经过特殊处理后的数据,FuncMap就可以使用起来的
模版:
header.tpl
{{define "header"}}
<html lang="">
<head>
<title>{{.Title}}</title>
</head>
<body>
{{end}}
index.tpl
{{template "header" .}}
<div>{{.Content}}</div>
<div>name: {{get "name"}}</div>
{{template "footer"}}
footer.tpl
{{define "footer"}}
</body>
</html>
{{end}}
在模版嵌套时,子模版需要指定相应的上下文才能正确的渲染{{template "header" .}}
,这里通过.
将所有数据传递到子模版
go部分代码如下:
type RenderFactory struct{}
func getValue(key string) string {
switch key {
case "name":
return "abelce"
case "sex":
return "male"
default:
return ""
}
}
func parseTemplate(tpl string) (*template.Template, error) {
header := "./template/header.tpl"
footer := "./template/footer.tpl"
file := "./template/" + tpl + ".tpl"
// 需判断文件是否存在
t := template.New(tpl + ".tpl")
t.Funcs(template.FuncMap{"get": getValue})
t, err := t.ParseFiles(file, header, footer)
if err != nil {
return nil, err
}
return t, nil
}
func (rf *RenderFactory) Render() error {
outputFile, err := os.Create("/data/index.html")
if err != nil {
return err
}
t, err := parseTemplate("index")
if err != nil {
return err
}
tmp := &Tmp{
Title: "go | template",
Content: "hello world",
}
err = t.Execute(outputFile, tmp)
if err != nil {
return err
}
return nil
}
完整代码github