'How do I create a table using Pugjs or Jade
I want to render this json file into the table using Pug but it doesn't happen as I want. I want the data in two languages and app_adi but only the latest data is coming. How can I display both?
JSON file
{
"accounts":{
"user":{
"_id":"5a500vlflg0aslf011ld0a25a5",
"username":"john",
"id":"59d25992988fsaj19fe31d7",
"name":"Test",
"customer":" John Carew",
},
"application":[
{
"app_id":"5af56pi314-y1i96kdnqs871nih35",
"language":"es"
},
{
"app_id":"5af56pi314-blvinpgn4c95ywyt8j",
"language":"en"
}
]
}
}
Code
body
main
.container
table.table
tr
th username
th customer
th language
th app_id
tbody
each users in accounts
tr
td #{users.user.name}
td #{users.user.email}
each app in application
td #{app.language}
td #{app.app_id}
I want to build this table:
username customer language app_di
john John Carew es 5af56pi314-y1i96kdnqs871nih35
en 5af56pi314-blvinpgn4c95ywyt8j
But when I run the above code I just get the last one, only language "en"?
How can I fix this?
Solution 1:[1]
Your issue has to do with where you're starting your each loop, but there are also some structural issues with your JSON.
I am assuming that you're passing the object into your route like this:
var data = { "accounts": ... }
res.render('templatename', data);
Which means that the accounts object will be at the root of your pug template when it is rendered.
When you create a loop on accounts (an object, not an array) pug will iterate over every property in that object, so your first each (each users in accounts) will give you these two values in the users variable:
- user
- application
I don't think that's what you want. If you converted the accounts.user segment into an array you could successfully loop through a set of users like this:
each user in accounts.users
As for the second, you will need to reference the application as follows:
each application in accounts.application
Alternatively, you might be passing the data into the render function like this:
var data = { "accounts": ... }
res.render('templatename', data.accounts);
If you do it this way then you will loop through the users like this:
each user in users
The application loop will be this:
each application in applications
Please take a quick look at the pug iteration docs for more reference.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Graham |
