最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
golang template实现模板layout及传递funcMaps
时间:2022-06-25 03:02:15 编辑:袖梨 来源:一聚教程网
golang template用法很简单:
tpl, _ := template.ParseFiles("templates/post.html")
tpl.Execute(w, nil)
但是一个模板的布局有很多公共的部分,通过我们会对template做layout,ParseFiles方法可以传入多个模板,如下实现:
layout.html
{{define "layout"}}
{{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的文件名,而非路径
相关文章
- TokenPocket钱包苹果版 05-03
- kdpay钱包app官网下载安卓版 05-03
- MGC钱包下载2024最新版 05-03
- 黑币钱包中文版 05-03
- 黑币交易所官网下载手机版 05-03
- 三国诛将录甄姬阵容搭配 05-03