Jasmine Ibikunle
Jasmine Ibikunle

Reputation: 139

I'm trying to read from a json file in my ejs template

I've got my data.json file and I want to read from the data stored in the file to './views/modules/header.ejs'. Ideally the data in the json file will be available to all modules in my project.

I'm using expressJs files and want to print the information from my json file to my web page. I've been able to load the data in my app.js file using the code below:

//import json
'use strict';
const fs = require('fs');
let jsonData = fs.readFileSync('data.json', 'utf8');
let data = JSON.parse(jsonData);
console.log(data.menu);

This is the content stored in the menu array:

"menu": [
    {
        "title": "Home",
        "link": ""
    },
    {
        "title": "Location",
        "link": ""
    },
    {
        "title": "Facilities",
        "link": ""
    },
    {
        "title": "Building details",
        "link": ""
    },
    {
        "title": "Floor plans",
        "link": ""
    },
    {
        "title": "Contact",
        "link": ""
    }
],

This is my header.ejs file:

<ul class="menu-list">
    <% for(var i=0; i < data.menu.length; i++) { %>
        <li><%= data.data.menu[i].title %></li>
    <% } %>
</ul>

I believe I'm missing a statement on my ejs file which will call the data. Thanks for your help in advance.

this is my index.js file looks like.

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Bank' });
});

module.exports = router;

Upvotes: 1

Views: 925

Answers (1)

Mahesh Bhatnagar
Mahesh Bhatnagar

Reputation: 1080

That code use in router file

router.get('/', function(req, res, next) {
  const fs = require('fs');
  let jsonData = fs.readFileSync('data.json');
  let data = JSON.parse(jsonData);
  let dataRecord = data.data;
  let dataRecordMenu=dataRecord.menu;
res.render('index', { title: 'Bank',data:dataRecordMenu });
});

That code use in view file

<ul class="menu-list">
      <% for(var i=0; i < data.length; i++) { %>
          <li><%= data[i].title %></li>
      <% } %>
  </ul>

Upvotes: 2

Related Questions