app.js initializes the allArticles as a global variable with the articles from the JSON file.
app.locals.allArticles = dataFile.articles;
articles.js (route) takes the app data and make it available in the articles.ejs page
router.get('/articles', function(req, res) {
var data = req.app.get('appData');
var articleTitles = data.articles;
res.render('articles', {
pageTitle: 'Articles',
pageID: 'articles',
articles: articleTitles
});
});
header.ejs references allArticles as follows
<% allArticles.forEach(function(item) { %>
<%= item.name %>
<% }); %>
Issue : reference to PageID or articles throws a reference error ie
allArticles is not defined
The weird thing is that the reference to pageTitle goes through..
You're passing a view variable named articles
to your view, not allArticles
. Rename one or the other so that they match and the error should go away.
You are passing articles
as an object not an array, the array of articles I think it's articleTitles
, so you could change the EJS code to:
<% articles.articles.forEach(function(item) { %>
<%= item.name %>
<% }); %>
Successfully passed data from the JSON file into the views as follows:
app.js made articles array available to local routes:
app.locals.allArticles = dataFile.articles;
index.js (route) took in app data, created array to hold data, passed through data using forEach function, rendered in view:
router.get('/', function(req, res) {
var data = req.app.get('appData');
var allArticles = [];
data.articles.forEach(function(item) {
allArticles = item.title;
});
res.render('index', {
pageTitle: 'Home',
pageID: 'home',
articles: allArticles
});
});
index.ejs (view):
<% allArticles.forEach(function(item) { %>
<%= item.name %><br/>
<% }); %>
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.