EJS include functions defined in a separate ejs file

烈酒焚心 提交于 2019-11-27 19:27:00

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/44141872/ejs-include-functions-defined-in-a-separate-ejs-file

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