如何使用 hogan-express 在 Node.JS 中呈现页面
How do I render a page in Node.JS with hogan-express
如何在节点中呈现页面(使用路由器),它只是将一个值传递给模板引擎供我使用?
例如(这是真正的代码):
var apiRouter = express.Router();
apiRouter.get('/myPosts', function(req, res){
userPostsModel.findOne({'profileID':req.session.facebookProfileId}, function(err, userPosts) {
if(userPosts) {
res.json({
posts : userPosts.posts
});
} else {
console.log('You do not have any posts');
}
})
})
以及模板引擎部分(html 文件):
<!doctype html>
<head>
<meta charset="UTF-8">
<title>My Posts</title>
</head>
<body>
<p><a href="/post?id={{posts.[0].postID}}">Post 1</a></p>
<p><a href="/post?id={{posts.[1].postID}}">Post 2</a></p>
</body>
</html>
我希望它能呈现页面,但我却得到了这个(在网页上):
{"posts":["12345667"]}
对于我的模板引擎,我使用 'hogan-express',如下所示:
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
我知道 res.json 在这里可能有误,但我对此一无所知。节点和路由器的文档无处不在!
正如@Molda 在下面的评论中所回答的,应该是这样的:
res.render('template-name', { posts:userPosts.posts});
试过了,对我有用。
如何在节点中呈现页面(使用路由器),它只是将一个值传递给模板引擎供我使用?
例如(这是真正的代码):
var apiRouter = express.Router();
apiRouter.get('/myPosts', function(req, res){
userPostsModel.findOne({'profileID':req.session.facebookProfileId}, function(err, userPosts) {
if(userPosts) {
res.json({
posts : userPosts.posts
});
} else {
console.log('You do not have any posts');
}
})
})
以及模板引擎部分(html 文件):
<!doctype html>
<head>
<meta charset="UTF-8">
<title>My Posts</title>
</head>
<body>
<p><a href="/post?id={{posts.[0].postID}}">Post 1</a></p>
<p><a href="/post?id={{posts.[1].postID}}">Post 2</a></p>
</body>
</html>
我希望它能呈现页面,但我却得到了这个(在网页上):
{"posts":["12345667"]}
对于我的模板引擎,我使用 'hogan-express',如下所示:
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
我知道 res.json 在这里可能有误,但我对此一无所知。节点和路由器的文档无处不在!
正如@Molda 在下面的评论中所回答的,应该是这样的:
res.render('template-name', { posts:userPosts.posts});
试过了,对我有用。