簡體   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