javascript HandleBars - 模板内的模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20299428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HandleBars - template inside templates
提问by kitimenpolku
I'm using handlerbars to create templates. Suppose that I'm doing a TODO list. I have a collection and I need also support for adding new TODO elements with the same style.
我正在使用处理程序来创建模板。假设我正在做一个 TODO 列表。我有一个集合,我还需要支持添加具有相同样式的新 TODO 元素。
So far I have a TODO template collection:
到目前为止,我有一个 TODO 模板集合:
<script id="TODO-collection-templ" type="text/x-handlerbars-template">
<div id="collection">
<ul>
{{#list todos}}
<li><span>{{this.title}}</span><span>{{this.description}}</span></li>
{{/list}}
</ul>
</div>
</script>
If I want to add new elements, the only way (to me) it would be creating another template that builds the following:
如果我想添加新元素,唯一的方法(对我来说)是创建另一个构建以下内容的模板:
<script id="TODO-templ" type="text/x-handlerbars-template">
<li><span>{{title}}</span><span>{{description}}</span></li>
</script>
So I end up having two templates but those are prone to errors (If I change something in TODO-collection-templ and I forget to do the same change over the TODO-templ, it will not render the Html properly)
所以我最终有两个模板,但它们很容易出错(如果我在 TODO-collection-templ 中更改了某些内容并且忘记对 TODO-templ 进行相同的更改,它将无法正确呈现 Html)
Is there any way to include the TODO-templ inside the TODO-collection-templ ??
有没有办法将 TODO-templ 包含在 TODO-collection-templ 中?
回答by MarcoL
There are partials in Handlebars like in Mustache's: http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers
在 Handlebars 中有部分像 Mustache 的:http: //blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers
Basically you can organise your micro-template as a partial and use it in the bigger template:
基本上,您可以将微模板组织为部分并在更大的模板中使用它:
<script id="TODO-partial" type="text/x-handlebars-template">
<li><span>{{title}}</span><span>{{description}}</span></li>
</script>
<script id="TODO-collection-templ" type="text/x-handlebars-template">
<div id="collection">
<ul>
{{#list todos}}
{{> TODO}}
{{/list}}
</ul>
</div>
</script>