在Golang中结合模板函数使用模板块

时间:2018-06-04 20:07:06

标签: templates go

我希望在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一次。 E. g。我没有按名称调用模板。

但是,我现在也想使用模板功能。现在我需要调用template.New来获取一个空模板,指定一个名称,添加模板函数并解析文件(Funcs&#34; must be called before the template is parsed&#34;):< / p>

tpl := template.Must(
    template.New("somename").Funcs(sprig.FuncMap()).ParseGlob("*.html")
)

这似乎与我对模板继承的想法不相容。我必须以ExecTemplatebase.html作为参数才能获得任何输出。但是,我想加载一个基本模板和许多内容模板。然后按名称调用内容模板。

我是否误解了Golang模板和/或Block的使用方式?什么是执行此类任务的优雅和惯用方式?

1 个答案:

答案 0 :(得分:1)

使用以下命令将模板功能添加到您已经使用的功能中:

t, err := template.New("base.html").Funcs(sprig.FuncMap()).ParseFiles("./templates/base.html", "./templates/blogpost.html")