EJS include functions defined in a separate ejs file

后端 未结 1 900
日久生厌
日久生厌 2021-01-14 04:40

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:

&l         


        
相关标签:
1条回答
  • 2021-01-14 05:07

    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.

    0 讨论(0)
提交回复
热议问题