EJS include functions defined in a separate ejs file

会有一股神秘感。 提交于 2019-11-29 11:52:55

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!