2

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

2 Answers 2

1

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>
    ...
Sign up to request clarification or add additional context in comments.

Comments

1

You can find you answer here:

how to print array in underscore.js template?

I'm copying the answer in case it will be removed:

My example looks like this (almost the same as you own):

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

with the following Javascript:

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

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

Just follow the example in your code.

I hope it will help you sort your issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.