I am developing small app with Express and PUG and I want to make like this:
index.pug
ul#restaurants-list
li
img.restaurant-img(alt='Mission Chinese Food', src='/images/reactchat.png')
h1
=`${name}`
p
='URL : ' + `${url}`
p
=`${explanation}`
a(href=`/${name}`) View Details
index.js
let express = require('express');
let router = express.Router();
let bodyParser = require('body-parser');
const fs = require('fs');
router.use(bodyParser.json()); // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// LowDB Module
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const shortid = require('shortid');
// Save DB in db.json
const adapter = new FileSync('./public/db.json');
const db = low(adapter)
db.defaults({
project: [],
cert: [],
education: []
})
/* GET home page. */
router.get('/', function (req, res, next) {
let data = db.get('project').find().value();
let sid = shortid.generate();
console.log(data);
res.render('index', {
dataarray: data,
id: sid,
name: data.name,
url: data.url,
explanation: data.explanation,
imgurl: data.imgurl
});
});
module.exports = router;
and I can make it one li element and it works but I have no idea how can I iterate the li element like the image. data are from JSON file and I get it with lowDB dependency.
db.json file looks like this
{
"project": [{
"name": "React Chat App",
"url": "https://sangumee.herokuapp.com/",
"explanation": "THis Project is good",
"imgurl": "images/reactchat.png",
"date": ""
},
{
"name": "React Chat App",
"url": "https://sangumee.herokuapp.com/",
"explanation": "THis Project is good",
"imgurl": "images/reactchat.png",
"date": ""
}
],
"cert": [],
"education": []
}
So the problem is How can I save multiple json data in index.js to get it to PUG file. And How can receive the multiple data from index.js and spread it in li element iteration.
I already check pug doc and several question that related with this problem but still I don't have idea.
You need to use the each
operator like this: (docs)
- var restaurants = dataarray.project
ul#restaurants-list
each restaurant in restaurants
li
img.restaurant-img(alt='Mission Chinese Food', src='/images/reactchat.png')
h1= restaurant.name
p= 'URL : ' + restaurant.url
p= restaurant.explanation
a(href= '/' + restaurant.name) View Details
That first line with the variable declaration points the iterator to where I believe the restaurants live in your route. You could also do it like this with no extra variables:
each restaurant in dataarray.project