Array with EJS Template in NodeJS

Our Goals –
• Sending Array to EJS Template

Assumption
We already have a NodeJs project “myschool” in our working directory. If you don’t have the project then please create it. We have discussed it on our previous tutorial.

To do so –

1. Open “app.js” and add the Array on it.

2. Open “home.ejs” file from “app_views” folder.
3. Edit it as –

<% include header %>
<body>
	<h1><%= topicHead %></h1>
	<ul>
	<% febChar.forEach(function( eachPerson){ %>
		<li> <%= eachPerson.fname %>  <%= eachPerson.lname %> </li>
	<% }) %>

	</ul>
</body>
<% include footer %>

4. Now browser will show our first EJS template based webpage @ http://localhost:5000/

5. And the console log is –

Source Code :

var express = require('express');
var parser = require('body-parser');
var path = require('path');
var app = express();
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'app_views'))
var person =[	
	{
		fname : 'Harold',
		lname : 'Finch'
	},
	{
		fname : 'John',
		lname : 'Reese'
	}
]

app.get('/',function(req,res){
	res.render('home',{
		topicHead : 'Person Of Interest TV Series',
		febChar : person
	});
	console.log('user accessing Home page');
});
app.listen(5000,function(){
	console.log('server running on port 5000');
})

Thank you.

Related posts:

2 thoughts on “Array with EJS Template in NodeJS”

Leave a Reply

Your email address will not be published. Required fields are marked *