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>
<% } %>
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>
<% } %>
Share
asked Nov 3, 2015 at 16:31
Daniel LizikDaniel Lizik
3,1442 gold badges23 silver badges44 bronze badges
3
- Your template should not be responsible for getting files! – Evan Davis Commented Nov 3, 2015 at 16:35
- @Mathletics this abstracted example isn't 100% reflective of the project I'm working on; I need to import data into this ponent which is then required by a main layout file. Regardless, I'm not fluent in EJS best practices. – Daniel Lizik Commented Nov 3, 2015 at 16:36
- I think this is an XY Problem, and I agree with @Eleanore's answer – Evan Davis Commented Nov 3, 2015 at 16:53
1 Answer
Reset to default 5You 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>
<% } %>