Using EJS as a template engine with ExpressJs

What is a template engine

Template engine is a tool to separate program-logic and presentation into two independent parts.This makes the development of both logic and presentation easier, improves flexibility and eases modification and maintenance.

If it is hard to understand, when we use a template engine we create a page with regular html and we add special tags (<%%>in EJS ) that will contain data or logic.

So when we use express we can use to different template engines.
  1. Jade
  2. EJS
I like EJS because it is very similar to normal HTML

Use EJS with express

First we need to install EJS using npm as a node module to our project.

npm install ejs --save

After installing EJS we need to provide the name of the template engine we are using in this project

var express = require('express');
var app = express();
app.set('view engine','ejs');


Then we can render the pages according to the requested route. The good thing is we can pass along information to our ejs template by sending a object with the render method.

app.get('/',function(req,res){
    res.render('default',{title:"Home"});
});

Here "default" is the name of the template file and by default express assumes it is in a folder called 'view'(Change the default view directory in ExpressJs).
Object that is the second parameter for render method contains details for display in the template.

Here is the "default" tamplate.

<!DOCTYPE>
<html>
<head>
      
</head>
<body>
   <h1><%=title %></h1>
  <p>Lorem ipsum dolor sit amet,</p>  
</body>
</html>

You can see some special tags are used inside h1 tags. So template engine recreate the HTML page by assigning data instead of logic inside tags.
After the recreation by template engine HTML will look like this.

<!DOCTYPE>
<html>
<head>
      
</head>
<body>
   <h1>Home</h1>
  <p>Lorem ipsum dolor sit amet,</p>  
</body>
</html>

Now you should be able to understand how template engines separate program-logic and presentation into two independent parts

No comments:

Post a Comment