简体   繁体   English

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

[英]Render each of multiple objects in array with Express in Node.js

I have multiple objects in array of locals in my routes and would like to render each at the time.我在我的routes的本地数组中有多个对象,并且想在当时渲染每个对象。

Example例子

// 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'
    }
  ]
}

Right now, this renders the last objects in array when I visit either link http://localhost:3000/posts/how-to-write-short or http://localhost:3000/posts/the-glamour-of-grammar .现在,当我访问链接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)

What's a better to render each eg routes.locals[0] , routes.locals[1] , and ...?渲染每个(例如routes.locals[0]routes.locals[1]和 ... )有什么更好的方法?

The optimal way is search the post id and pass it to the render:最佳方法是搜索帖子 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);
  }
});

You could do the following:您可以执行以下操作:

In your code在你的代码中

app.get(routes.path, function(req, res) {
    res.render(routes.view, routes.locals)
})

take from req the id and pass it to the res.render.从 req 中获取 id 并将其传递给 res.render。 Then you should select only the local that you are interested in and this should do the trick.然后你应该只选择你感兴趣的本地,这应该可以解决问题。

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

Hope this will help you.希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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