[英]Render each of multiple objects in array with Express in Node.js
我在我的routes
的本地數組中有多個對象,並且想在當時渲染每個對象。
例子
// 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-to-write-short
或http://localhost:3000/posts/the-glamour-of-grammar
時,這會呈現數組中的最后一個對象.
// 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]
和 ... )有什么更好的方法?
最佳方法是搜索帖子 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);
}
});
您可以執行以下操作:
在你的代碼中
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)
})
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.