5

テンプレートに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 }));

ここでの私の質問は、ループ コードを記述する必要がありますか? コレクションを渡すだけでなく、コレクション内のアイテムごとに 1 つのアイテムをレンダリングするのに十分スマートなアンダースコアを使用することはできませんか? また、underscore.js はテンプレートをネストするためのものを提供していますか? コレクション内の各アイテムには、実際にはレンダリングする必要があるアイテムのコレクションもあります。このテンプレート内から別のテンプレートを呼び出すにはどうすればよいですか。もちろん、リンク、ヒント、チュートリアルは大歓迎です。

ありがとう!

4

3 に答える 3

5

ループ コードを記述する必要があると思いますが、テンプレートではなくビューにループを配置することでクリーンアップできます。したがって、( を保持する) コンテナー用の 1 つのテンプレートと、<ol>をレンダリングするため<li>の別のテンプレートがあります。

各アイテムがアイテムのコレクションである場合は、同じ手法を使用して、それらのモデルを<ol class="topic-collection-will-append-to-this">トピック アイテム テンプレートの に追加できます。

私は以下のコードをテストしなかったので、100% バグがないわけではありませんが、それに取り組む方法のアイデアが得られるはずです :)

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>
于 2011-10-18T21:50:33.723 に答える
0

あなたが探しているのは、より有能なテンプレート システムです。Underscore のテンプレートは非常に最小限であり、ループなどの組み込みサポートはありません。Maybee の口ひげのテンプレートはあなたにぴったりですか? (補足: 奇妙な理由でロジックレスと呼ばれています。再帰とラムダの両方のサポートにより、Scheme の少なくとも半分に達したと言えますが、脱線します..)

于 2011-10-19T10:57:41.263 に答える