<p>I am struggling to find out how to execute a template, say "layout", that needs other sub-templates to work.</p>
<p>"layout" needs: "navbar", "content", "footer"</p>
<p>I have different files like "index.gohtml" where "content" is defined, "navbar_public.gohtml" where "navbar" is defined but also at the same time "navbar_user.gohtml" where "navbar" again is defined.</p>
<p>Is there any way to execute the template "layout" with specific template files without having to parse them again?</p>
<p>My current solution (which I want to avoid):</p>
<pre><code>utils.GenerateHTML(w,
data,
"templates/blog/layout.gohtml",
"templates/blog/navbar.gohtml",
"templates/blog/index.gohtml",
"templates/blog/footer.gohtml",
)
</code></pre>
<p>where</p>
<pre><code>func GenerateHTML(w http.ResponseWriter, data interface{}, filenames ...string) {
var files []string
for _, file := range filenames {
files = append(files, file)
}
templates := template.Must(template.ParseFiles(files...))
err := templates.ExecuteTemplate(w, "layout", data)
if err != nil {
log.Fatalln(err)
}
}
</code></pre>
<p>Grateful for anything that puts me in the right direction. </p>
<hr/>**评论:**<br/><br/>: <pre><p>[deleted]</p></pre>afghanPower: <pre><p>Wow. That was an elegant solution. Much appreciated.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传