一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

golang template实现模板layout及传递funcMaps

时间:2016-03-10 编辑:简简单单 来源:一聚教程网

golang template用法很简单:
tpl, _ := template.ParseFiles("templates/post.html")
tpl.Execute(w, nil)

但是一个模板的布局有很多公共的部分,通过我们会对template做layout,ParseFiles方法可以传入多个模板,如下实现:
layout.html
{{define "layout"}}


   
    Title


{{template "body" .}}


{{end}}

post.html
{{template "layout" .}}
{{define "body"}}


    this is body

{{end}}

golang实现(将主模板作为第一个参数)语句如下:
tpl, _ := template.ParseFiles("templates/post.html", "templates/layout.html")
tpl.Execute(w, nil)

如果传入funcMap:
var funcMaps = template.FuncMap{
    "empty": func(str string) bool {
        if str == "" {
        return true
        } else {
        return false
        }
    },
}
 
 
tpl, err := template.New("post.html").Funcs(funcMaps).ParseFiles("templates/post.html", "templates/layout.html")
if err != nil {
    //...
}
 
tpl.Execute(w, nil)

这里要特别注意的是New方法的参数是最外层container的文件名,而非路径

热门栏目