Javascript 使用Node.js中的Express渲染数组中的多个对象
我在我的Javascript 使用Node.js中的Express渲染数组中的多个对象,javascript,arrays,node.js,express,object,Javascript,Arrays,Node.js,Express,Object,我在我的路线中有多个局部变量数组中的对象,我希望每次都进行渲染 示例 // routes.js const routes = { path: '/posts/:id', view: 'posts', locals: [ { id: 'how-to-write-short', title: 'How to write short', description: 'The art of painting a thousand pictures
路线中有多个局部变量数组中的对象,我希望每次都进行渲染
示例
// routes.js
const routes = {
path: '/posts/:id',
view: 'posts',
locals: [
{
id: 'how-to-write-short',
title: 'How to write short',
description: 'The art of painting a thousand pictures with just a few words',
date: '23 Mar 2018',
issue: '1'
},
{
id: 'the-glamour-of-grammar',
title: 'The glamour of grammar',
description: 'A guide to the magic and mystery of practical English',
date: '01 April 2018',
issue: '2'
}
]
}
现在,当我访问任一链接http://localhost:3000/posts/how-写简短的
或http://localhost:3000/posts/the-语法的魅力
// server.js
const express = require('express')
const routes = require('./routes')
const app = express()
app.set('views', 'src/pages')
app.set('view engine', 'js')
app.engine('js', require('./engine'))
app.get(routes.path, function(req, res) {
res.render(routes.view, routes.locals)
})
app.listen(3000)
渲染每个路由(例如routes.locals[0]
,routes.locals[1]
,和…?您可以执行以下操作:
在代码中
app.get(routes.path, function(req, res) {
res.render(routes.view, routes.locals)
})
从req获取id并将其传递给res.render。然后,您应该只选择您感兴趣的本地文件,这样就可以了
app.get(routes.path, function(req, res) {
const id = req.params.id;
const local = routes.locals.filter(local => local.id === id)
res.render(routes.view, local)
})
希望这将对您有所帮助。最佳方法是搜索帖子id并将其传递给渲染器:
app.get(routes.path, (req, res) => {
const id = req.params.id;
const post = routes.locals.find(p => p.id === id);
if (post) {
res.render(routes.view, post);
} else {
res.render(routes.post_not_found_view);
}
});
你的问题不是很清楚……请结帐,并获取如何编写一个大家都能回答的好问题的指南。如果我敢打赌,我会说您使用的模板或视图有一些错误,并且没有将locals
视为数组。把它也挂起来,因为我认为这会有很大帮助。