最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Retrieve local JSON file data in EJS template - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 5

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>
<% } %>
发布评论

评论列表(0)

  1. 暂无评论