需要的下划线模板帮助-模板集合



我使用underscore.js作为模板。下面是一个示例模板。

<script id="discussion-template" type="text/html">
    [[ _.each(discussions, function(topic){ ]]
       <li>
           <article id="{{ topic.htmlId() }}">
               <a class="section-arrow mir" href="#">toggle</a>
               <h3>{{ topic.get('text') }}</h3>
               <ol></ol>
           </article>           
       </li>
    [[ }); ]]
</script>

在一个backbone.js view.render()中,我将一个集合传递给模板。

this.el.append(this.template({ discussions: this.collection.models }));

我的问题是,我必须写循环代码吗?我可以不只是传递一个集合和下划线是聪明到足以渲染一个项目在集合中的每个项目?另外,underscore.js是否为嵌套模板提供了一些东西?集合中的每个项目实际上都有一个我需要渲染的项目集合。如何从这个模板中调用另一个模板?任何链接,提示,和/或教程当然是非常感谢。

谢谢!

我认为您必须编写循环代码,但您可以通过在视图中而不是模板中使用循环来清理它。因此,您将有一个用于容器(保存<ol>)的模板和另一个用于呈现<li>的模板。

对于作为项目集合的每个项目,您可以使用相同的技术,将这些模型附加到主题项目模板中的<ol class="topic-collection-will-append-to-this">

我没有测试下面的代码,所以我不是100%它不是没有bug的,但它应该给你一个解决它的方法的想法:)

window.TopicView = Backbone.View.extend({
    template: _.template($("#topic-template").html()),
    tag: 'li',
    className: 'topic',
    initialize: function() {
        _.bindAll(this, 'render');
    },
    render: function() {
        $(this.el).html(this.template({topic: this.model}));
        return this;
    }
});
window.DiscussionView = Backbone.View.extend({
    tagName: 'section',
    className: 'discussion',
    template: _.template($('#discussion-template').html()),
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.bind('reset', this.render);
    },
    render: function() {
        var $topics,
        collection = this.collection;
        $(this.el).html(this.template({}));
        $topics = this.$(".topics");
        this.collection.each(function(topic) {
            var view = new TopicView({
                model: topic
            });
            $topics.append(view.render().el);
        });
        return this;
    }
});
<script id="topic-template" type="text/html">
    <article id="{{ topic.htmlId() }}">
        <a class="section-arrow mir" href="#">toggle</a>
        <h3>{{ topic.get('text') }}</h3>
        <ol class="topic-collection-will-append-to-this">
        </ol>
    </article>           
</script>
<script type="text/template" id="discussion-template">
    ...
    <ol class="topics">
    </ol>
</script>

可以有两个模板,一个用于列表,另一个用于内部元素。在列表模板中,只打印内部的结果:http://jsfiddle.net/dira/hRe77/8/

下划线的模板非常非常简单,没有任何智能行为/魔法附加:http://documentcloud.github.com/underscore/docs/underscore.html#section-120

您正在寻找的是一个更胜任的模板系统。Underscore的模板非常小,没有内置循环等支持。也许小胡子模板更适合你?(旁注:由于一些奇怪的原因,它被称为"无逻辑"。有了对递归和lambda的支持,我想说你至少完成了Scheme的一半,但我离题了…)

最新更新