簡體   English   中英

需要下划線模板幫助 - 模板集合

[英]Underscore templating help needed - templating collections

我正在使用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/

Underscore的模板非常簡單,並沒有附加任何智能行為/魔術: http//documentcloud.github.com/underscore/docs/underscore.html#section-120

您正在尋找的是一個更有能力的模板系統。 Underscore的模板非常小,沒有內置的循環支持等。 Maybee Moustache模板更適合你? (旁注:由於一些奇怪的原因,它被稱為無邏輯。有了遞歸和lambda支持,我會說你至少是Scheme的一半,但我離題了..)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM