简体   繁体   中英

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?

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)
<%}%>

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>

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