Execute a list of previously parsed templates

xuanbao · · 336 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I am struggling to find out how to execute a template, say &#34;layout&#34;, that needs other sub-templates to work.</p> <p>&#34;layout&#34; needs: &#34;navbar&#34;, &#34;content&#34;, &#34;footer&#34;</p> <p>I have different files like &#34;index.gohtml&#34; where &#34;content&#34; is defined, &#34;navbar_public.gohtml&#34; where &#34;navbar&#34; is defined but also at the same time &#34;navbar_user.gohtml&#34; where &#34;navbar&#34; again is defined.</p> <p>Is there any way to execute the template &#34;layout&#34; 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, &#34;templates/blog/layout.gohtml&#34;, &#34;templates/blog/navbar.gohtml&#34;, &#34;templates/blog/index.gohtml&#34;, &#34;templates/blog/footer.gohtml&#34;, ) </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, &#34;layout&#34;, 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

336 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传