golang template用法很简单:
tpl, _ := template.ParseFiles("templates/post.html")
tpl.Execute(w, nil)
但是一个模板的布局有很多公共的部分,通过我们会对template做layout,ParseFiles方法可以传入多个模板,如下实现:
layout.html
{{define "layout"}}
post.html
{{template "layout" .}}
{{define "body"}}
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的文件名,而非路径
摩托车销售模拟器内置菜单中文版
摩托车出售模拟器,又名摩托车销售模拟器,这是一个以摩托车销售
船舶模拟2020最新版
船舶模拟2020是玩法非常有意思的模拟驾驶游戏,高清3d画质
油管主播的生活2内置菜单版
油管主播的生活2内置菜单版是一款模拟养成类游戏,在这里你将体
网吧老板模拟器2手机版
网吧老板模拟器2是非常受欢迎的模拟经营题材手游,在原本的基础
美国警察模拟器巡警2024最新版
美国警察模拟器是一款好玩的模拟手游,游戏中你将扮演一位警察,