EJS变量定义问题

时间:2016-12-01 01:47:05

标签: javascript node.js express ejs

尝试一下节点,但我无法获取EJS模板来渲染一些非常基本的数据。我有两个控制器 - 一个用于基本家庭/关于/联系,另一个用于帖子。当我到达/发布时,正确的页面呈现但没有该数据,并且出现错误,表示“帖子未定义”。我不明白为什么会这样。欢呼声。

    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;

和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>

和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);

1 个答案:

答案 0 :(得分:1)

您需要确保在呈现页面时将posts变量传递给页面,以便将该变量传递给EJS模板:

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

// ...