在模板里面的把手模板

时间:2012-08-08 16:05:31

标签: javascript mustache handlebars.js

如何在手柄中的模板内创建模板?
这些是我的模板:

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

我想在动态模板中的运行时(cat-template或dog-template)加载适当的模板。我怎么能这样做?

2 个答案:

答案 0 :(得分:7)

Partials 在您拥有需要在几个不同背景下使用的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

答案 1 :(得分: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>