Using EJS as a Template Engine in your Express App

Using EJS as a Template Engine in your Express App

Hello and Welcome!🤓

in this article, I’ll show you how to add js code into HTML using EJS with Node.js express framework. If you are new to template engines then I will recommend you to check out my previous blog👉 Introduction to template engines.

Normally you could use NodeJS for your backend application and use a front-end development framework like Angular, VueJS, React, etc But in this case💁‍♀️ For a quick NodeJS application, we could also just use a view engine like EJS. Of course, there are a lot of alternatives to EJS, but that’s one of the more popular options and that’s why we are going to use it😯.

Template Engines💥

A quick intro to the template engine👇,

A template engine is software designed to combine templates with a data model to produce, in our case, real HTML code.

Template engines handle the task of interpolating data into HTML code while providing some features (like partials in EJS) that would have been difficult to replicate by concatenating strings.

What is EJS?🧐

Introducing EJS💣, EJS is one of the most popular template engines for JavaScript. One of the reasons to choose it is that EJS code looks like pure HTML🤓.

It retains the syntax of HTML while allowing data interpolation, unlike Pug (another template engine) which uses a different syntax with indentation and spaces.

EJS files are saved with the .ejs file extension.

Embedded JavaScript Templates (EJS) are used as a lightweight solution for creating HTML markup with simple JavaScript code. Fast code execution 💥 and ease of debugging make this the perfect templating engine for those who want to do HTML work with their favorite language, probably JavaScript.

No religiousness about how to organize things and no reinvention of iteration and control flow. It uses just plain JavaScript.

It features:👇

  • Fast compilation and rendering

  • Simple template tags: <% %>

  • Both server JavaScript and browser support

  • Static caching of intermediate JavaScript

  • Static caching of templates

  • Complies with the Express view system

How to use the EJS template engine with the Express JS

STEP 1☝️: SETTING UP A PROJECT.

  • Open up the terminal and create the project directory.
mkdir ejs-sample
  • Then, navigate to the directory.
cd ejs-sample
  • Now, initialize npm init.
npm init -y
  • Let’s install npm modules we will need to build the application.
npm i -S express ejs

After installing the EJS, now inside your app folder create a new folder and name it `views` since EJS looks into the ‘views’ folder for the templates to render.

Before creating files let’s take a look at the app folder structure –

Basically, in the views folder, we’ll create our views.

STEP 2✌️: CONFIGURING app.JS.

When we have all the required modules, create an app.js file.

After installing EJS and Express the first thing we should do is create a web server using Express to set EJS as our view engine.

const express = require('express');
const app = express();

// setup view engine
app.set('view engine', 'ejs');
  • After creating the ‘views’ folder make a file named “index.ejs”.

Add a ‘h1’ tag in the index.ejs file so we can show our context. Now we have to render this page on request with Express. To add dynamic content you have to write the second parameter which is an object.

//route for index page
app.get("/", function (req, res) {
  res.render("index",{title:"Hello Folks! welcome to Chhakulis Blog"});
});

In this case, I used ‘title’ and gave it a Hello Folks! welcome to Chhakulis Blog value. Before getting to displaying our dynamic content we should listen to our server.

app.listen(8080, function () {
  console.log("Server is running on port 8080 ");
});

Now, we can embed ‘title’ into our index.ejs file. The EJS tag we are gonna be using is <%= %> . The EJS file should look like this.

<!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</title>
</head>
<body>
    <h1><%= title %></h1>
</body>
</html>

When we run our app you should see the ‘Hello Folks! welcome to Chhakulis Blog’ text in localhost:8080. If we change the title value the value seen on the website would also change.

  • The final look of our app.js
const express = require('express');
const app = express();

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

//route for index page
app.get("/", function (req, res) {
  res.render("index"),{title:"Hello Folks! welcome to Chhakulis Blog"});
});

//listen to the port
app.listen(8080, function () {
  console.log("Server is running on port 8080 ");
});

Let’s understand what this code does🕵️‍♀️.

  • We are importing Express module and declaring its instance as an app.

  • We are setting up a server to listen port 8080 by using app.listen().

  • We are telling our server to use the EJS template engine in line,
    app.set(“view engine”, “ejs”).

  • We also set up a route / to render the index EJS page.

You can notice that our server shows user HTML content by using res.render(). Note that this res.render method will look for EJS files in the views directory so we only have to give the file name overall path will be interpreted as /views/index.

STEP 2👌:Final Output😍

Conclusion 🙆‍♀️

To sum up, EJS is a very good template engine that is made for Node.JS. I think using EJS is good because of these reasons:

  • Basic, Easy to Use

  • Speeds Up Web Development Period

  • Flexible

Thanks for reading all the way to the end!

Happy Coding :)❤️

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!