2014-07-03 40 views
0

我試圖讓我的json數據追加到模板中。在我的模板中會有幾個對象,我使用的是{{#each products}}。 Json數據似乎出現在控制檯中,但模板中的數據沒有任何反應。Json數據不是追加流星模板使用每個

這裏是我的JS:

if (Meteor.isClient) { 
    Template.product_items.products = function() { 
    Meteor.call('getProducts', function(error, result){ 
     var products = JSON.parse(result.content).products; 
     console.log(products); 
    }) 
    } 
} 


if (Meteor.isServer) { 
    Meteor.startup(function() { 
    Meteor.methods({ 
     getProducts: function(){ 
     return HTTP.call("GET", "https://api.url.com/products", 
      {params: {access_token: "***"}}); 
     } 
    }); 
    })} 

我的觀點:

<body> 
    {{> product_items}} 
</body> 

    <template name="product_items"> 
    {{#each products}} 
    <div class="col-md-3"> 
    <img src="{{preview_url}}" class="img-thumbnail"> 
    <h4>{{name}}</h4> 
    <p>{{description}}</p> 
    <p> 
     <a href="{{short_url}}">More</a> 
    </p> 
    </div> 
    {{/each }} 

</template> 

console.log(products);給了我正確的數據:

[Object, Object] 
    0: Object 
    description: "<p>it's what you need</p>" 
    name: "wow product" 
    preview_url: "erl.jpg" 
    webhook: null 
    __proto__: Object 
    1: Object 
    description: "<p>okok</p>" 
    name: "wow nemr" 
    preview_url: "surl.jpg" 
    webhook: null 
    __proto__: Object 
    length: 2 
    __proto__: Array[0] 

,但它沒有出現在模板。我究竟做錯了什麼?先謝謝你。

回答

2

您需要返回您的值從Template.product_items.products函數。當然,當你使用方法時,這不是直接可能的,因爲方法在客戶端上是異步的。你需要利用幫手的反應性。

實施例:

var products = null; 
var productsDep = new Tracker.Dependency(); 

Template.product_items.rendered = function() { 
    products = null; 
    Meteor.call('getProducts', function(error, result) { 
    products = JSON.parse(result.content).products; 
    productsDep.changed(); 
    }); 
}; 

Template.product_items.helpers({ 
    products: function() { 
    produtsDep.depend(); 
    return products; 
    }, 
}); 
+0

'Template.product_items.products = ...'被棄用。改爲使用'Template.product_items.helpers(...)'。 – nilsi

+0

@nilsi當然。我更新了答案(這很舊,你看)。 'Deps'現在也是'Tracker'。 –

+0

完美,感謝您的更新! – nilsi