简体   繁体   中英

Retrieve local JSON file data in EJS template

My project looks like this:

views/
    layout.ejs
data/
    US-states.json
public/
    index.html

US-states.json looks like this

{
    "DC": "District of Colombia",
    "NY": "New York",
    etc...
}

How can I pull this json data into layout.ejs to render some divs in a loop like this?

<div>DC: District of Colombia</div>
<div>NY: New York</div>

I tried something like this but I'm having trouble googling the solution:

var data = JSON.parse('./../data/US-states.json')
<% for(var p in data) {%>
   <div>p: data[p]</div>
<% } %>

You should not retrieve data from the view. Thus, when you have retrieved it in the backend, you pass the JavaScript object representing your data (as the one you cited in your question) to the EJS from the business layer. I do not know what you are using as a backend framework. For instance, when using NodeJS:

response.render("yourEJS", {data: yourObject});

Then, in your view, you traverse the object via JavaScript:

<% for (aProperty in data) { %>
    <div> <% aProperty %>: <%data[aProperty]%> </div>
<% } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM