Search code examples
javascriptjqueryunderscore.jsunderscore.js-templating

Javascript templates using underscore.js


I have a phones array that contains data from json:

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
        },    

I want display it as ul li by using template but I'm completely new at this and so I'm stuck. Here a code that I'm wrote:

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

Problem is that i instead of displaying image it gives me path of that image:

   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

Solution

  • Obviously, if you print a url to screen, that is what you will see. If you want to see an image, that is what you have to print, an <img>. And use the url as the src attribute.

    Changing your template to something like this should do the trick:

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