3

如何在车把的模板内创建模板?
这些是我的模板:

<script type="text/x-handlebars-template" id="animal-template">
    <div class="locationSelect">
    {{content}}
    </div>
</script>
<script type="text/x-handlebars-template" id="cat-template">
    <div>
    I am cat
    </div>
</script>
<script type="text/x-handlebars-template" id="dog-template">
    <div>
    I am dog
    </div>
</script>

我想在运行时在动物模板中加载适当的模板(猫模板或狗模板)。我怎样才能做到这一点?

4

2 回答 2

7

当您需要在几个不同的上下文中使用大量 Handlebars.js 模板时,部分会派上用场

<script id="people-template" type="text/x-handlebars-template">
  {{#each people}}
    {{> person}}
  {{/each}}
</script>

<script id="person-partial" type="text/x-handlebars-template">
  <div class="person">
    <h2>{{first_name}} {{last_name}}</h2>
    <div class="phone">{{phone}}</div>
    <div class="email"><a href="mailto:{{email}}">{{email}}</a></div>
    <div class="since">User since {{member_since}}</div>
  </div>
</script>

<script type="text/javascript">
  $(document).ready(function() {
    var template = Handlebars.compile($("#people-template").html());
    Handlebars.registerPartial("person", $("#person-partial").html());

    template(yourData);
  }
</script>

http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers

于 2013-12-19T00:21:24.880 回答
2

您可以templateName根据呈现的项目计算 的项目视图属性:

App.AnimalView = Ember.View.extend({
  templateNameBinding: function () {
    var kind = this.get('animal.kind');
    return '%@-template'.fmt(kind);
  }.property('animal.kind')
});

然后在容器模板中,通过它们的视图渲染项目:

<script type="text/x-handlebars-template" id="animal-template">
  <div class="locationSelect">
  {{#for animal in content}}
    {{view App.AnimalView animalBinding="animal"}}
  {{/for}}
  </div>
</script>
于 2012-08-08T16:13:17.877 回答