Passing Data to EJS Template

Passing Data to EJS Template

When using an EJS (embedded JavaScript) template, you must note it differs from using vanilla JavaScript in certain ways. The most important differences is the execution of a variable that isn't defined in the index.js file before being passed to the EJS file for use. Let's take a look at a simple code below written in an EJS file, provided that an imaginary variable called 'data' is undefined.

<% if (data) { %>

<h1> data is defined </h1>

<% } else { %>

<h1> data is undefined </h1>

<% } %>

The above code will generate an error. Reason for this is because, EJS tries to execute this code immediately and finds out that there is no information or value ascribed to data, so it generates an error because it executed an undefined variable first without scoping all written code to better understand what was demanded of it. So how do we correct this?

We can take care of this error by using an inbuilt variable called 'locals'. What locals does is that, it enables the EJS to first scope through all the written code before execution. By doing this, EJS can now understand that though data wasn't defined, there is still an action it can perform when data is undefined. So we fuse the locals variable together with our undefined variable like how it's done below:

<% if (locals.data) { %>

<h1> data is defined </h1>

<% } else { %>

<h1> data is undefined </h1>

<% } %>

By writing your statement like it's done above, fusing your locals variable with your undefined variable like objects, your code gets executed properly without error.