Hi. In this tutorial, I will show you how start using template engines in your node js/express js applications. Template engines are the easiest ways to get started with building your express js application. I recommend you check out our video content and other useful resources on our YouTube channel and this blog respectively.
NB: Basic node js/express knowledge required for this tutorial
What is template engine?
In simple terms, a template engine is a package that renders data in HTML pages. It easily allows us to create and use static html page.
One particularity with template engines is their ability to inject data from the server into an html template and then send the final html page to the client side. In other words, a variable can be created in our server and then be inserted in an html template.
We have several examples of template engines which are usable with node js and express js which include:
- Pug
- Handlebars
- EJS
- Hogan etc
With simplicity in syntax and structure, template engines can be used as a quick tool to easily get started with a Node js application if you don’t want to do anything complex or involve other front-end frameworks like React JS or Vue JS.
In this tutorial, we will use discuss about EJS template engine.
To add EJS in your Express JS project, you must install the module in order to start using it. To install EJS module, navigate to your project directory from a command prompt window and type the command:
After hitting enter, just wait for a while as npm downloads and installs it in your local machine. please take note this requires internet.
Usage
As example, we are going to setup a simple express app that renders a web page with variables using EJS.
To begin using EJS in our express app, we must import/call EJS and set view engine as EJS in our code. You will understand better when you see in code ☺.
Finally, at the route handler, you just render the file using the method re.render() which takes as parameter the EJS file name (without extension) and the variable.
EJS files have the extension .ejs and contains html which has portions of server variables written in EJS syntax. This EJS file is stored in a folder called views where express checks by default for rendering web pages.
Take note of the fact that, though express js has the ability to respond to a request by sending a file, it can not really inject a variable into the html template just like EJS did.
Enough of the talking, let’s do the coding ☺
Create a folder called views in your node js project directory.
server.js
- Notice how a string value was assigned to variable title.
index.ejs
- Notice how I represented the variable in the HTML code.
- EJS uses the syntax <%= … %> to represent variables in HTML code.
OUTPUT
Thanks for coding with me.
Comments
Post a Comment
Please do not enter any spam link in the comment box.