Benjamin Barbé
Benjamin Barbé

Reputation: 271

Can't access to json values into ejs template

I have a EJS template where i want to use my json data.

My json look like:

{
  "menu": {
    "id": "file",
    "value": "File"
  },
  "menu2": {
    "id": "file",
    "value": "File"
  }
}

After i export my json in my nodejs app to be able to use this json everywhere because it will be in my navbar:

const navigation = require('./templates/partials/header/navigation.json');


app.use(function (req, res, next) {
    app.locals = {
        navigation: navigation
    };
....
});

And I use my use my data in my partial:

<%for(let el in navigation){%>
console.log(el) //return 'menu1' & 'menu2'
console.log(el.id) //return undefined & undefined
<%}%>

The problem is the second console.log, it return undefined values I don't know why, any ideas?

Upvotes: 2

Views: 954

Answers (2)

Michel Novellino
Michel Novellino

Reputation: 383

additionally with express, if you declare a local variable you can access from any part of your controller using the req object

const navigation = require('./templates/partials/header/navigation.json');

   app.locals.navigation = navigation;

   router.get("/your_route", function(req, res, next) {
    res.status(200).json(req.app.locals.navigation)
   })

and You can also pass it as a property,

   router.get("/your_route", function(req, res, next) {
      res.render("your_template_name", {
       navigation:req.app.locals.navigation
      });
   })

  <ul
     <% navigation.forEach(function(el) { %>
     <li><%= el.value %></li> 
     <% }); %>
  </ul>

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074475

el is a string, not the object. for-in loops through the property names in the object, not their values. To access the value of the property using a for-in loop, you'd have to use the el via brackets notation (navigation[el]):

<%for(let el in navigation){%>
console.log(navigation[el].id)
<%}%>

But in any modern environment, you could use Object.values and for-of instead, if you don't need the property names:

<%for(let el of Object.values(navigation)){%>
console.log(el.id)
<%}%>

If you need the property names, either continue using for-in (but correctly), or use Object.entries, perhaps with destructuring:

<%for(let [name, value] of Object.entries(navigation)){%>
console.log(name, value.id)
<%}%>

Upvotes: 4

Related Questions