IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    golang template实现模板layout及传递funcMaps

    mckee发表于 2016-03-06 16:33:22
    love 0

    golang template用法很简单:

    tpl, _ := template.ParseFiles("templates/post.html")
    tpl.Execute(w, nil)

    但是一个模板的布局有很多公共的部分,通过我们会对template做layout,ParseFiles方法可以传入多个模板,如下实现:
    layout.html
    {{define "layout"}}
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    {{template "body" .}}
    </body>
    </html>
    {{end}}

    post.html
    {{template "layout" .}}
    {{define "body"}}
    <div>
        this is body
    </div>
    {{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的文件名,而非路径。



沪ICP备19023445号-2号
友情链接