I use express.js
in my nodejs web app, user input some condition, and the program get an array of data such as this:
var data = [
{
name: 'Salmons Creek',
image: 'https://farm6.staticflickr.com/5479/11694969344_42dff96680.jpg',
description: "Great place to go fishin' Bacon ipsum dolor amet kielbasa cow"
},
{
name: 'Granite Hills',
image: 'https://farm5.staticflickr.com/4103/5088123249_5f24c3202c.jpg',
description: "It's just a hill. Made of granite. Nothing more! Cow doner."
},
{
name: 'Wildwood Miew',
image: 'https://farm5.staticflickr.com/4016/4369518024_0f64300987.jpg',
description: 'All campsites. All the time.Short ribs pastrami drumstick.'
},
{
name: 'Lake Fooey',
image: 'https://farm7.staticflickr.com/6138/6042439726_9efecf8348.jpg',
description: 'Hills and lakes and lakes and hills. Pork ribeye pork chop.'
}
];
I want to use the EJS template language to render all the objects in the array. How can I pass the data to the template and render them?
In your js file you should render the ejs like this:
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.use("/", express.static(__dirname + '/'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
var data = [
{
name: 'Salmons Creek',
image: 'https://farm6.staticflickr.com/5479/11694969344_42dff96680.jpg',
description: "Great place to go fishin' Bacon ipsum dolor amet kielbasa cow"
},
{
name: 'Granite Hills',
image: 'https://farm5.staticflickr.com/4103/5088123249_5f24c3202c.jpg',
description: "It's just a hill. Made of granite. Nothing more! Cow doner."
},
{
name: 'Wildwood Miew',
image: 'https://farm5.staticflickr.com/4016/4369518024_0f64300987.jpg',
description: 'All campsites. All the time.Short ribs pastrami drumstick.'
},
{
name: 'Lake Fooey',
image: 'https://farm7.staticflickr.com/6138/6042439726_9efecf8348.jpg',
description: 'Hills and lakes and lakes and hills. Pork ribeye pork chop.'
}
];
res.render('index.ejs', {data:data} );
});
app.listen(8080);
And in your ejs file you can render the data variable like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<ul>
<% data.forEach(function(dat) { %>
<li><%= dat.name %></li>
<li><%= dat.image%></li>
<li><%= dat.description%></li>
<% }); %>
</ul>
</body>
</html>
I have tried it and it works.
The folder structure is like this:
.
+-- app.js
+-- views
| +-- index.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With