Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJS include functions defined in a separate ejs file

I am trying to include an ejs file that contains functions for setting up my views. These functions were defined to be used a helpers. I have tried using:

<% include helpers.ejs %>

But when I try to use the function from this file:

<% module_start('$body', [{name:'display',value:'block'}], 'body'); %>

I get the error:

Reference Error: module_start is not defined

When I copy over the code from 'helpers.ejs' to my original view file, 'test.ejs', it works as expected. I have gone through several answers and, am still confused what am I doing wrongly in this case.

Thanks for your help in advance.

like image 534
Abrar Hossain Avatar asked Sep 16 '25 00:09

Abrar Hossain


1 Answers

After some grueling hours of trying every conceived solutions out there, I have landed upon a solution that is working. The solution was borrowed from:

EJS Functions

Looking at the solution presented in this code, I updated my 'helpers.ejs' to 'helpers.js'. Following this, I added the exported functions from 'helpers.js' to the ejs render context object:

const ejs_helpers = require('path/to/helpers.js');

...

ejs.renderFile('filename', { helpers:ejs_helpers, ...}, (err,data)=>{});

In the ejs view file:

<%- helpers.function_name(params); %>

This considerably changes how I initially approached the problem. With plain ejs helper file, the functions include HTML in between the control flow statements. In the case presented here, the functions returns plain string. Notice the '-' with the 'Scriptlet' tag.

Hope this helps someone.

like image 133
Abrar Hossain Avatar answered Sep 17 '25 21:09

Abrar Hossain