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

Hca*_*tek 5 javascript templates backbone.js underscore.js backbone-relational

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

在backbone.js view.render()里面我将一个集合传递给模板.

this.el.append(this.template({ discussions: this.collection.models }));
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

kre*_*eek 5

我认为你必须编写循环代码,但你可以通过在视图而不是模板中使用循环来清理它.所以你有一个容器的模板(持有<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>
Run Code Online (Sandbox Code Playgroud)


dir*_*ira 5

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

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