我希望在Golang中使用模板块来获得“模板继承”风格的覆盖逻辑。
我有一个类似如下的base.html
模板:
<title>{{block "title" .}}Default Title{{end}}</title>
<body>{{block "content" .}}This is the default body.{{end}}</body>
然后我有一个模板blogpost.html
,如下所示:
{{define "title"}}Blog Post Title{{end}}
{{define "content"}}Lorem Ipsum...{{end}}
只要我使用ParseFiles
,然后执行模板,所有这些都可以完美地工作
t, err := template.ParseFiles("./templates/base.html", "./templates/blogpost.html")
t.Execute(t, viewModel)
我这样做的方式是为我需要渲染的每个模板调用一次ParseFiles
。例如,我没有按名称调用模板。
但是,我现在还想使用模板函数。现在我需要调用template.New
来获取一个空模板,分配一个名称,添加模板函数并解析文件(Funcs
"must be called before the template is parsed"):
tpl := template.Must(
template.New("somename").Funcs(sprig.FuncMap()).ParseGlob("*.html")
)
这似乎与我对模板继承的想法不兼容。为了获得任何输出,我必须使用base.html
作为参数进行ExecTemplate
。但是,我想加载一个基本模板和许多内容模板。然后按名称调用内容模板。
我是不是误解了Golang模板和/或块的使用方式?执行这类任务的优雅和惯用的方式是什么?
发布于 2018-06-05 05:12:19
使用以下方法将模板函数添加到已有的工作中:
t, err := template.New("base.html").Funcs(sprig.FuncMap()).ParseFiles("./templates/base.html", "./templates/blogpost.html")
https://stackoverflow.com/questions/50688031
复制相似问题