0

テンプレートコード:

<script type="text/template" id="baseTemplate">
        <% collection.each(function() { %>
            <div>
                <%= collection %>
            </div>
        <% }); %>
</script>
<div id="baseContainer"></div>

および他のコードは:

//model
var PageModel = Backbone.Model.extend({
    defaults: {
        "id":null,
        "title":"",
        "content":""
    },
});
//collection
var PageCollection = Backbone.Collection.extend({
    defaults: {
        model: PageModel
    },
    model: PageModel,
    url: 'api/get_page/?id=6'
});
//view
var PageView = Backbone.View.extend({

    el: $('#baseContainer'),

    initialize: function () {
        this.collection = new PageCollection();
        this.collection.bind("reset", this.render, this);
        this.collection.bind("change", this.render, this);
        this.collection.fetch();
    },
    render: function () {

    var html = _.template($("#baseTemplate").html(), { collection: this.collection });
    this.$el.html(html);
    console.log(html);
    return this;
    }
});

 var page = new PageView();

問題は、その戻り値とオブジェクトがオブジェクトから値を取得するにはどうすればよいかということです。apiリンクはhttp://furqankhanzada.com/backbonejs/api/get_page/?id=6、ブラウザコンソールでオブジェクトを確認できます。http://furqankhanzada.com/backbonejs/ タイトル、コンテンツ、添付ファイル->画像->ギャラリーラージ-> url(each()を使用した添付ファイル)を取得する必要があります。

4

1 に答える 1

1

これが適切な解決策であるかどうかはわかりませんが、試してみることができます。

代替案は次のようになります。

var html = _.template($("#baseTemplate").html(), { models: this.collection.models });

コレクションを直接渡すのではなく、モデルを渡します。そして、テンプレートでは、次のようなことができます。

<script type="text/template" id="baseTemplate">
  <% _.each(models, function(mdl) { %>
    <div>
      <%= mdl.get('title') %>
      <%= mdl.get('content') %>
      <% _.each(mdl.get('page').attachments, function(attachment) { %>
        <%= attachment.images["Gallery Large"].url %>
     <% }) %>  
   </div>
  <% }); %>
</script>
<div id="baseContainer"></div>

必要に応じてマークアップを変更してください。しかし、この解決策は問題に固有のものです:( :(

于 2012-11-03T07:43:12.980 に答える