HandleBars-模板中的模板

HandleBars - template inside templates

本文关键字:HandleBars-      更新时间:2024-01-18

我正在使用handlerbar创建模板。假设我正在做一个TODO列表。我有一个集合,我还需要支持添加具有相同样式的新TODO元素。

到目前为止,我有一个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>

如果我想添加新元素,(对我来说)唯一的方法就是创建另一个模板来构建以下内容:

<script id="TODO-templ" type="text/x-handlerbars-template">
    <li><span>{{title}}</span><span>{{description}}</span></li>
</script>

因此,我最终得到了两个模板,但它们很容易出错(如果我更改了TODO集合templ中的某些内容,却忘记了对TODO templ进行相同的更改,它将无法正确呈现Html)

有没有办法将TODO templ包含在TODO集合templ中??

Handlebars中有类似Mustache的分部:http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers

基本上,你可以将你的微模板组织为一个部分,并在更大的模板中使用:

<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>