aqp aqp - 7 days ago 3
Javascript Question

EJS variable definition issue

Trying my hand at a bit of node but i can't get my EJS template to render some very basic data. I have two controllers - one for basic home/about/contact and another for posts. When i got to /posts, the correct page renders but without that data and an error appears saying that "posts is not defined." I don't understand why this is the case though. Cheers.

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

var posts = [{
id: 0,
title: "This is an example post.",
author: "Tony",
content: "This is some content for a post"
}];

router.get('/', function(req, res) {
res.render("posts/index");
});

router.get('/new', function(req, res) {
res.send("NEW");
});

router.get('/:id', function(req, res) {
res.send("SHOW");
});

router.post('/', function(req, res) {
res.send("CREATE");
});

router.get('/:id/edit', function(req, res) {
res.send("EDIT");
});

router.put('/:id', function(req, res) {
res.send("UPDATE");
});

router.delete('/:id', function(req, res) {
res.send("DELETE");
});


module.exports = router;


And the html:

<!DOCTYPE html>
<html>
<head>
<title>Posts</title>
</head>
<body>
<h1>hello</h1>
<nav>
<ul>
<li><a href="/posts">Posts</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
<%= posts %>

<% for(var i=0; i < posts.length; i++) { %>
<%= posts[i].id %>
<h2><%= posts[i].title %></h2>
<h4><%= posts[i].author %></h4>
<p><%= posts[i].content %></p>
<% } %>

<button><a href="/posts/new">New</a></button>

</body>
</html>


and app.js

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.PORT || 3000;
var router = require("./config/routes");
var posts = require("./config/posts");

// Set the view directory to /views
app.set("views", __dirname + "/views");

// Let's use the Express templating language
app.set("view engine", "ejs");

// Setup public folder to serve static files
app.use(express.static(__dirname + "/public"));

// Setup app to parse req.body
app.use(bodyParser.urlencoded({
extended: true
}));

app.use('/', router);
app.use('/posts', posts);

app.listen(port);

Answer

You need to make sure you pass in the posts variable to the page when it's being rendered in order to get that variable to the EJS template:

var posts = [{
  id: 0,
  title: "This is an example post.",
  author: "Tony",
  content: "This is some content for a post"
}];

router.get('/', function(req, res) {
  res.render("posts/index", {
    posts: posts
  });
});

// ...