教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 golang template实现模板layout及传递funcMaps

golang template实现模板layout及传递funcMaps

发布时间:2017-12-11   编辑:jiaochengji.com
教程集为您提供golang template实现模板layout及传递funcMaps等资源,欢迎您收藏本站,我们将为您提供最新的golang template实现模板layout及传递funcMaps资源
本文章来为各位介绍一篇关于golang template实现模板layout及传递funcMaps的例子,希望此教程能够对各位带来帮助的哦。

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的文件名,而非路径

您可能感兴趣的文章:
golang template实现模板layout及传递funcMaps
Golang 模板(text/template) (一)
golang 模板(template)的常用基本语法
golang模板(text/template)
php模板引擎有哪些
一文读懂Django中的views.py和html之间的参数传递关系
jQuery布局插件UI Layout简介及使用方法
PHP模板引擎smarty生成随机数 smarty中math函数用法
jquery.mustache.js使用
Json2Template.js 基于jquery的插件 绑定JavaScript对象到Html模板中

[关闭]
~ ~