Node.js Templating with EJS – Basics

Node.js Templating

JavaScript LogoEJS Makes Templating in your Node.js application a breeze. Just supply a template string or .ejs file and some data.

The moniker says it all: “Effective JavaScript templating.” If you haven’t already discovered it, you’ll soon find that as front-end web developers have been transitioning to more of a full-stack role, templating has quickly become an important topic. In other words, this is no longer an unusual front-end task for JavaScript developers. And when working with Node.js, EJS has become the standard for server-side templating.

In this article, I will cover the bare-bones steps needed to get up and running with EJS, and in doing so, I’ll show you how to render data in an EJS template. First, I’ll explain the vanilla JavaScript approach. Then, we’ll move on to rendering your EJS template when using the Express.js framework. And finally, we’ll cover the syntax for EJS template code as well as how to use “if” logic in your template.

Now the power in EJS templates is the separation of concerns. Your data is defined (and possibly manipulated) in your server-side code, and your template simply declares what data will be rendered. This approach embraces the concept of “loose coupling”. With EJS templates, you can leverage that same “loose coupling” design pattern in your Node application. This scenario is, of course, fairly common to back-end developers, who have experience with languages such as Java, PHP, Python or .NET. For a front-end developer, however, this may be new territory. So, to illustrate, let’s take a look at some examples.

Example # 1-A

Example # 1-B: The Rendered HTML

In Example # 1 – A we first require the ejs module. This will be the case with every example, so I won’t cover that again. Just know that we need the ejs module in order to render our EJS templates, so we set a variable named “ejs” via require first. Next, we set the days variable; it’s just an array that contains the five days of the work week. Here, too, this will be the case in every example, so no need to cover this again. Just know that in each code example, there is a days variable – an array that contains the five days of the work week. We also set a variable named “http” which is an instance of the Node http module. We’ll need this in order to run our web server.

Okay, so let’s take a look at line # 3 in Example # 1. We’re using the ejs.render method here to create HTML that we will send to the user. The ejs.render method takes two arguments: a string template and the data for that template. In this case, our string template has the “<%=” and “%>” delimiters to indicate to EJS the start and end points for our template. And inside of those delimiters, we can write JavaScript code. So, let’s use the join() method of the days array to convert the array to a string. Then, inside of the execution of the http.createServer method, we’ll call the end method of the result object (i.e. res.end), passing the html variable to that method. And since the res.end() will send the response to the client and end the connection, the contents of our html variable will be sent to the user’s browser. Now, in Example # 1 – B, we have the HTML that is rendered in the user’s browser. This HTML happens to be very simple, and in fact, is not markup that we’d want to use in production. But what I wanted to demonstrate here is that rendering HTML in an EJS template is as simple as defining the template, then providing data to that template.

Example # 2-A: Setting the view engine for Express.js

Example # 2-B

Example # 2-C: The Rendered HTML

In Example # 2-A we’re leveraging the Express.js framework, so there’s a new require statement at the top of our code which sets the Express variable. On line # 3, we create the app variable which is an instance of the Express.js framework. And on line # 9, we use the app.set method to tell Express that we’re using EJS as our view engine. Note that this is required when leveraging EJS templates in your Express application. Now, on line # 12, we set up a handler for the “/” route. And inside that handler callback, we use the render method of the response object. This render method is available to use because of what we did on line # 9: using the app.set method to let Express know that EJS is our view engine. Okay, so let’s go back to line # 13, where we’ll pass two arguments to the render method: the string “example-2” and the data that our EJS will consume.

Now, you may be scratching your head as to what the first argument in “Example # 2-A” means. Well, it’s important to note that when you leverage EJS as your view engine, Express.js assumes that you will have view templates. These view templates are text files with an “.ejs” extension. So, it’s also important to note that Express.js assumes that these files will be in a folder named “views” that resides in the same folder as the file that is currently being executed. You can specify a different folder for your views, but the default folder that Express will look for is “views”. And in the “views” folder, Express.js will look for a file named XXX.ejs, where “XXX” represents the string that you pass as the first argument to the render method. So in our example, we want to use a template that resides in the file: “views/example-2.ejs”.

Here in Example # 2-B, we have the contents of the file “views/example-2.ejs”. And in this template file, there are two locations for data; the title tag and the body tag. In the title tag, we have a binding for the headerTitle property. In other words: we’ve provided some data to the res.render() method on line # 13 of Example # 2-A. That data was an object literal, and it had a property named: “headerTitle”. So, on line # 3 of our “views/example-2.ejs” file, we’ve told the template to inject the value of the “headerTitle” property of the data object that was provided to it. And the same thing is happening in line # 6 of our “views/example-2.ejs” file. In other words, we’ve asked EJS to inject the value of the “welcomeMessage” property of the data that was provided to the template. And then in Example # 2-C, you see the HTML that is returned to the user’s browser as a result of our template in Example # 2 B. In this HTML, the “headerTitle” property binding is replaced by the actual value: “EJS Demo Page” and the “welcomeMessage” property binding is replaced by the actual value: “This message was rendered on the server.”

Now, Example # 3-A is very similar to Example # 2-A, except that the data we provide to the template is an array, instead of just an object literal. If you look at Example # 3-B, you’ll see that the way we bind to the data differs from example # 2-A. In example # 2-A, we bound to a single property: “welcomeMessage”, but here we are using a loop to iterate over each element in the “days” array. Specifically, we use the forEach() method of the “days” array and in each iteration of the callback function, we have access to a variable named “day”. Then we generate a list item and output the value of “day”. So, if you look at Example # 3-C, you’ll see the HTML that is rendered by the server and sent to the user’s browser. Voila! As expected, we have the HTML with the unordered list rendered with each day of the week (i.e. the “days” array).

Example # 4-A is virtually identical to Example # 3-A; the only difference is the value of the “welcomeMessage” property. Take a look at Example # 4-B. You’ll see that on line # 4, we have some custom CSS in a set of style tags. This will make more sense in a few minutes. Now look at line # 20. Here we are looping over the “days” array, just as we did in Example # 3-B. But on line # 22, we use a basic JavaScript “if” block, to determine if this is the fourth element in the array. We do that by using the index variable, which is the 2nd argument passed to the callback function that we provide to the days.forEach() method. So, if index is equal to 3, then we generate the following in our HTML: class=”selected”. What we are doing here is, we are telling our EJS template that the 4th element in the list (i.e. the element with the index of 3) should have the CSS class “selected”. So, in Example # 4-C, you can see in the rendered HTML that the fourth list item has class=”selected“. As a result, the CSS that we added at the top of the EJS template kicks-in and “Thursday” is dark red text with a yellow background.

Summary

So, in this article, you learned the most basic steps needed to leverage an EJS template in your Node.js application. You started by learning how to render data in an EJS template using vanilla JavaScript, and also when using the Express.js framework. Then we went on to cover how to bind a single data property, as well as how to iterate an array in your template. And finally, we wrapped it up by illustrating how to use “if” logic in your EJS template.

Now this article only scratched the surface of what is possible with EJS templates. My goal here was simply to provide the information needed to get up and running quickly, and to illustrate the most basic concepts so that you can dig in further on your own, because, believe me, there is plenty more to discover on this topic!