繁体   English   中英

在 Node.js 中使用 Express 渲染数组中的每个对象

[英]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-shorthttp://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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM