2

我有一個手機數組,其中包含從JSON數據:的Javascript模板underscore.js

var phones = [ 
     { 
      "age": 0, 
      "id": "motorola-xoom-with-wi-fi", 
      "imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg", 
      "name": "Motorola XOOM\u2122 with Wi-Fi", 
      "snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb).", 
      "price": 150 
     },  

我想通過使用模板顯示爲UL李,但我在這是全新的,所以我很卡住。 這裏說,我寫了代碼:

<div id="phonesDiv" class="col-md-8"></div> 

<script type="text/template" id="listTemplate"> 

    <ul> 
     <% for (var i=0; i< phones.length; i++) { %> 
     <li><%=phones[i].age %></li> 
     <li><%=phones[i].name%></li> 
     <li><%=phones[i].id%></li> 
     <li><%=phones[i].imageUrl%></li> 
     <li><%=phones[i].snippet%></li> 
     <li><%=phones[i].price%></li> 
     <% } %> 
</ul> 

var temp = _.template($("#listTemplate").html()); 
var getPhones = temp({phones: phones}); 
$("#phonesDiv").html(getPhones); 

問題是我,而不是顯示圖像它給我的形象的路徑:

0 
Motorola XOOM™ with Wi-Fi 
motorola-xoom-with-wi-fi 
img/phones/motorola-xoom-with-wi-fi.0.jpg 
The Next, Next Generation Experience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb). 
150 

回答

1

顯然,如果你打印一個網址到屏幕上,那就是你會看到的。如果你想看到一張圖片,那你必須打印一張<img>。並使用url作爲src屬性。

改變你的模板,以這樣的事情應該做的伎倆:

... 
    <li><img src="<%=phones[i].imageUrl%>" alt="<%=phones[i].name%>" /></li> 
    ... 
1

你可以在這裏找到答案:

how to print array in underscore.js template?

我複製的情況下,答案也將被刪除:

我的例子看起來是這樣的(幾乎是你自己的一樣):

<script type='text/template' id="bunny-template"> 
    <div> 
    <h5><%= name %></h5> 
    <ul> 
     <% for(var tag in tags) { %> 
      <li><%= tags[tag] %></li> 
     <% } %> 
    </ul> 
    </div> 
</script> 

與以下Javascript:

bunny_data = { 
    name: "sprinkles", 
    age: 1, 
    tags: ['fuzzy','wuzzy'] 
}; 

bunny_view = $("#bunny-template").html(); 
$(body).append(_.template(bunny_view, bunny_data)); 

只需按照代碼中的示例操作即可。

我希望它能幫助你排序你的問題。