Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a data array from express.js to ejs template and render them

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?

like image 215
vag Avatar asked Mar 08 '23 04:03

vag


1 Answers

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
like image 154
Víctor Beltrán Avatar answered Apr 24 '23 05:04

Víctor Beltrán