Render array of objects in Jade / Pug

2020-06-18 01:29发布

问题:

I don't find a lot of stuff for Pug / Jade templating, so I try here. I've been reading the documentation for iterations and also this link here.

I'm working with Node.js, Express, and pug. So far I have some function server side that collect some data about users (I'm building a fake dating website as a school project) So my code server side looks like this :

router.post('/matchaSearch', function (req, res) {
  matchaSearch(pool, session.uniqueID)
     .then((results) => {

       res.results = JSON.stringify(results)
       console.log('result', results)
       res.render('./userMatch', {res})
       })
     .catch((err) => {
       console.error('error', err)
       res.status(500).send("we don't have any suggestions for you so far")
       })
     })

I can log results in iterm and all my data is here, but when it comes to client side it's kinda different.

h1
 |Here are your suggestions
script.
 console.log(!{res.results}[0].username)
ul
  for username in res.results
    li= username

Here I can log the first username from res.results in my browser's console, but in my page my li is rendering :

Here are your suggestions

.[

.{

."

.i

.d

."

.:

.3

.3

can you understand my problem here ? it's showing every char from my array of objects. I just wanted to show the username as a link so I can display a suggestion page with some suggested users.

I was wondering if maybe I can use jquery to render so html into my li and then call it but I'm facing a wall here as well. Any help is more than welcome ! Thanks.

回答1:

{res} does not make any sense to javascript. you should provide template an object include key/value pairs:

res.render('./userMatch', {results: results})

and then your loop in template becames:

ul
  for item in results
    li= item.username


回答2:

    h1
     |Here are your suggestions
    script.
     console.log(!{res.results}[0].username)
    ul
      for username in res.results
        li= username.username

i think username is object and you are printing that whole