gpt4 book ai didi

javascript - EJS变量定义问题

转载 作者:行者123 更新时间:2023-12-03 05:32:02 25 4
gpt4 key购买 nike

尝试使用一些 Node ,但我无法让我的 EJS 模板呈现一些非常基本的数据。我有两个 Controller - 一个用于基本的主页/关于/联系方式,另一个用于帖子。当我到达/posts 时,会呈现正确的页面,但没有该数据,并且出现错误,提示“帖子未定义”。我不明白为什么会这样。干杯。

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

最佳答案

您需要确保在渲染页面时将 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
});
});

// ...

关于javascript - EJS变量定义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40901312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com