How to use Ejs includes & partials

June 7, 2023


Ejs Includes & Partials


Includes & partials in ejs allow you to include html templates into your app. In this example, we're going to include a header into our index ejs file. First, we're going to create a folder called partials, then we're going to make a header.ejs file & add our code.

Creating the header.ejs file

Next, we're going to create the index.ejs file. We're going to put the include function where the header would be. The include function takes two arguments,

The first a string, it's a path to the partial file which can be either absolute or relative.

The second is an object, that is data that can be passed to the partial.

The index.ejs file with the include function in it


Passing Data to the Template


We can also pass data to the template using the second argument of the include function.

Passing data to the partial with the include function

We can grab that data & use it in the partial. A partial shares the same data as the parent view.

Using the data in the partial


Using Scripts in Ejs


You can use any script that you would be able to use in javascript in ejs. We're going to make another header called header2.ejs & use an if statement to pass the header that we want into our index page. The header will have most of the same content except 1 nav link will be missing. Make sure you begin & close every ejs script tag with <% %>. Define a variable called flag & set it to true. Then, we're going to make the if statement, if the flag is true we're going to show header2.ejs, else we're going to show header.ejs.

Using scripts in ejs

With all the new tech coming out, ejs is still simple & powerful to use.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.