Hello everyone! Today I'm going to discuss about  another major basic topic comes along with Express framework.. It's about Template Engines. What is it? Simply it's an easy way to bind the data into views.
Like we code using HTML, here we have similar kind of coding..Only the syntax matters according to each template engine.
Examples:
Blade Engine  - used with Laravel
Pug Engine     - used with Express
EJS Engine     - used with Express

Since we are focusing on Express, I will now explain the difference of some template engines used with Express/ NodeJS.

Prerequisites :
We created a server in the previous article. If you have missed it, click on the below link to read the article.
create-simple-web-server-with-express

Please follow all the steps. Then it will be get connected with this article. Run the server using node app.js command.
So, we will use this server for further explanations. You can see the function that loads the home route..Can't you?

app.get('/', function (req, res) {
    res.send('hello world')
});

Here we sent a HTTP response using res command to print hello world on the root page. It's ok.. But think if you need to load a file as the root view..Can you use the same way? Nooo..
Now we have to render a view file or we can call its as a template! We need to use a different method. It's render() function.

EjsTemplate Engine

Imagine that I have a file called index.ejs as the root view. How to do this?

First we need to install ejs node_module into our project. Open the project in VS Code. Use integrated terminal in VS code to enter npm commands. Otherwise you can use windows cmd and go into your project using cd commands. Then run the following command. It will install the module.

npm install ejs --save

So, now we are ready to use EJS Template Engine guys! Next step is to introduce ejs engine to our project. Open app.js and enter the below line of code.

app.set('view engine', 'ejs');

Our task is not over! Then we need to tell the path to our views to the server. For this now I create a new folder within the project folder called views. Then I introduce this to the server using this command.

app.set('views', path.join(__dirname, 'views'));

Now server knows about EJS!
You are ready to use render function now! This is the way..Replace the route function with this one.
app.get('/', function (req, res) {
    res.render('index');
});

Let's code the content for index.ejs file.
EJS Template Engine have a lot of similarities with HTML and plus some additional features. Only the main difference is the way of printing values, calling for loops, using conditional statements and etc. All these are data binding ways..
I will explain!

views/index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>EJS Template</title>
</head>
<body>
    <h1>Hello Express</h1>
</body>
</html>

We need to stop the server and restart! You got this view with h1 tag?

Now you will say the index.ejs file just contains HTML Tags.. Why can not we use HTML?
In Node JS, we have to pass data and bind them in views.. Like we do in PHP..
<?php echo $title ?>
Here I didn't bind any data in the view. So you will say so..When we need to display some dat passed through the server, we use EJS SYNTAX!
Next I will show you how to pass a data into EJS template and to bind it.
Now I'm going to pass some data with the rendering function.
What is the syntax for passing data?
res.render('view_name', {
    data 1: "value 1",
    data 2: "value 2"
});
What is the syntax for displaying data with EJS Syntax?
<%= data 1 %>
<%= data 2 %>

I pass two data when I render my view index.ejs. Modify the function is app.js.

app.get('/', function (req, res) {
    res.render('index', {
        title: "Hello Express",    
        name: "Techpool"    
    });
});

Next step is to get these two data into the view. Modify the index.ejs view.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>EJS Template</title>
</head>
<body>
    <h1><%= title %></h1>
    <h1>My name is <%= name %></h1>
</body>
</html>

You can see the values I passed through the server now! I think you got the way!

I have told that there are several Template Engines. EJS is only one template. Only the way of displaying values  + structure of coding will change. Server functions remain as same..

Pug Template Engine

I'm going to code the same index file using this engine. in the views folder, create a file called index.pug. As we did in the introducing part of EJS, we need to do those steps here also.
Install PUG Engine
npm install pug --save
Introduce PUG Engine
app.set('view engine', 'pug');

views/index.pug

<!DOCTYPE html>
html(lang="en")
    head
        meta(charset="UTF-8")
        meta(name="viewport", content="width=device-width, initial-scale=1.0")
        meta(http-equiv="X-UA-Compatible", content="ie=edge")
        title Document
    body

    h1 #{title}
    h1 My name is #{name}

Look at the structure of the page! You will get the same output..

There's no more use of HTML here! Only starting tags are there! No ending tags! That's why I told the syntax matters according to each template engine.
How to display data in pug?
#{ data 1 }
#{ data 2 }

PUG has a less coding style..But it's difficult to adopt it's style at once..But EJS is easy as it's like HTML.

In this article, I talk about only two template engines..There are more..Search in Google and you will find more results.

But remember you can use only one Template Engine in a project!

So, I have explained the basics about the way to use template engines with Node JS.. Next part is an interest tip for you to follow in every Express project.

Nodemon

This is a monitor for any change in the NodeJS file. You started the server by typing node app.js on cmd or terminal. But when you modify the files, those modifications are not considered by the server.  Because the server has been started already.. So, you have to stop the server and restart after any change you do in the project. This is a mess!
Isn't it? Here you get the solution : nodemon

First Install this monitor into your project. Type the following command after you going into the project using cmd.
npm install -g nodemon

Then you can start the server just typing the command   nodemon.
See the result...


When you do any change, it will keep track of all changes. If there are no errors, It will successfully start the server automatically with the latest changes. If there are errors, it will log them on the cmd.
So this is simply Nodemon!

We have come to the end of this article guys! I think I have clearly explained the basics of Template Engines used in NodeJS and the importance of Nodemon. Try to use these tips when you do a project in Express.

Good Bye Guys!



1 Comments

  1. Nice Explanation sir and more importantly everything works like magic. God bless you

    ReplyDelete