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)); 

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

我希望它能帮助你排序你的问题。