bhansa
bhansa

Reputation: 7504

Getting value fron json in ejs file

Below is my json file, I want to put src for my img element.

How can I access value from my json using keys img1, img2, img3... as I am already looping through.

json file:

{
  "img1": "http://yui.yahooapis.com/testassets/museum.jpg",
  "img2": "http://yui.yahooapis.com/testassets/uluru.jpg",
  "img3": "http://yui.yahooapis.com/testassets/katatjuta.jpg",
  "img4": "http://yui.yahooapis.com/testassets/morraine.jpg",
  "img5": "http://yui.yahooapis.com/testassets/japan.jpg"
}

Ejs file:

<% var img_content = JSON.parse(json['img-load.json']); %>
<body>
    <% for(var i = 1; i <= 5; i++ ) { %>
        <img id="img<%= i %>" src="<%= img_content[i] %>" />
    <% } %>
</body>
</html>

Upvotes: 0

Views: 57

Answers (1)

skirtle
skirtle

Reputation: 29102

I think you need img_content['img' + i], like this:

<% var img_content = JSON.parse(json['img-load.json']); %>
<body>
    <% for(var i = 1; i <= 5; i++ ) { %>
        <img id="img<%= i %>" src="<%= img_content['img' + i] %>" />
    <% } %>
</body>
</html>

The [] work just the same as they would in normal JS code.

Upvotes: 1

Related Questions