Reputation: 13
I have webpage rendered in handlebars and express. The data is driven by a JSON document that has two objects, one is a set of dates and the other contains details. Each date dynamically creates a web page with the required data. Below is a simple example of the data I am working with.
JSON
{
"calendar": {
"jan01": {
"date": "January 1st",
"weather": "cloudy"
},
"jan02": {
"date": "January 2nd",
"weather": "sunny"
},
...
"dec31": {
"date": "December 31st",
"weather": "cloudy"
}
},
"weatherDetails": {
"sunny": {
"img": "https://sunny image"
},
"cloudy": {
"img": "http://cloudy image"
}
}
}
I am passing the data from express via the following:
routes.get('/day/:date', (req, res) => {
const urlDate = req.params.date
res.render('day', {
day: calendar[urlDate].date,
weather: calendar[urlDate].weather
})
I can pull the actual word (sunny or cloudy) but I want to also get the corresponding image link in the weatherDetails object.
I am not sure where to start thinking of the solution. Whether it is to create a new object by merging the data on matching names or is there a helper function in handlebars that can do this.
Upvotes: 0
Views: 336
Reputation: 406
I am assuming calendar here is the object for the calendar key in your JSON object and so you have another variable called weatherDetails that has the object for the weatherDetails key in your JSON object.
Why not just resolve the image and pass it in as another key in the object you are passing in to the render function
routes.get('/day/:date', (req, res) => {
const urlDate = req.params.date
res.render('day', {
day: calendar[urlDate].date,
weather: calendar[urlDate].weather,
weatherImage: weatherDetails[calendar[urlDate].weather].img
})
This is assuming that all the weather conditions are accounted for in the weatherDetails object in the JSON file.
Upvotes: 0