<p>Hey gophers,</p>
<p>I know I can have a base template like </p>
<pre><code>{{define "base"}}
<head>
{{template "head" .}}
</head>
<body>
{{template "body" .}}
</body>
</code></pre>
<p>And I can fill in the nested templates like </p>
<pre><code>{{define "head"}}<title>{{.Title}}</title>{{end}}
{{define "body"}}<h1>{{.Title}}</h1>{{end}}
</code></pre>
<p>But how would I keep this flexible enough to avoid errors in all the different handlers, as soon as I start adding more kinds of nested templates to it?</p>
<p>E.g. now I want to add a footer. I'd have to go through all handlers and add</p>
<pre><code> html := template.ParseFiles("templates/_base.tmpl", "templates/single.tmpl", "templates/footer.tmpl")
</code></pre>
<p>to the files that get parsed. Is there some kind of mechanism or pattern to use?</p>
<p>Thanks!</p>
<hr/>**评论:**<br/><br/>anoland: <pre><p>The usual way to do this is grab (glob()) all the templates at once and add them to a map of [string]template one by one.</p>
<p><a href="https://elithrar.github.io/article/approximating-html-template-inheritance/">https://elithrar.github.io/article/approximating-html-template-inheritance/</a></p>
<p>I've tried this and it is easy to understand but I found it somewhat inverted and hard to implement in what I actually wanted to do.</p>
<p>Instead I've settled on <a href="https://github.com/unrolled/render">github.com/unrolled/render</a> since it is simple to add to my projects.</p></pre>gotemplates: <pre><p>Brilliant, thank you! Both of these links answer my question, I'll see which way suits my app better. </p>
<p>Didn't think to search for "composable" or "inheritance", and that first article doesn't mention "nesting".</p></pre>blueblank: <pre><p>Check out how this was accomplished with <a href="https://github.com/thrisp/djinn" rel="nofollow">Djinn</a>.</p></pre>gotemplates: <pre><p>Thanks, interesting. I think this first of all needs some documentation and samples outside of the tests and quickstart.</p></pre>THUNDERGROOVE: <pre><p>I've always defined a base template name</p>
<pre><code>const base = "base.tmpl"
</code></pre>
<p>Then I use ioutil.ReadDir to look into my templates directory and iterate over them.</p>
<pre><code>if !v.IsDir() && v.Name() != Base {
var err error
Templates[v.Name()], err = template.ParseFiles(filepath.Join("templates", v.Name()), filepath,Join("templates", Base))
... Check error ...
}
</code></pre>
<p>Not the best if you need to have more than one base template. But it works for me.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传