2

file 1: ejsfunction.ejs

<% function funcTest() {return 42;} %>

file 2: file.ejs

<% include ejsfunction.ejs %>
<% funcTest(); %>

output:

ReferenceError:
    1| <% include ejsfunction.ejs %>
 >> 2| <% funcTest(); %>
funcTest is not defined

Hi, I am working on a node.js/express project and trying to refactor some functions out of an ejs file into a second file, and then use the include directive to load them back in. Unfortunately, I am doing something wrong as I keep getting a ReferenceError with the code above.

Can anybody tell me what I am doing wrong, please?

Many thanks in advance! Dan.

DanJHill
  • 167
  • 2
  • 12
  • 1
    [Look this](https://stackoverflow.com/questions/5404830/node-js-ejs-including-a-partial) – Mukhammadsher Oct 03 '19 at 10:01
  • 1
    I'm not sure if EJS supports calling functions that way. I can't see any example of that at https://ejs.co/#docs. It looks like you have to turn function into a template, and include it wherever you want to "call" it. – ahwayakchih Oct 03 '19 at 10:01
  • Re Mukhammadsher's comment: thanks for the link. I actually already am using partials in my project and that works fine. However, I am not referencing any functions in those partials from the second file. – DanJHill Oct 03 '19 at 10:06
  • Just to clarify: in my very simple example above, it looks like I could just pass a function in to the ejs from my regular javascript code - however, in my real code I really do need the ejs functionality - not just regular javascript. – DanJHill Oct 03 '19 at 10:08

1 Answers1

1

After some time, I have not worked out how to do my original ask, but I have found a work around.

If you want to factor out commonly used functions into a separate partial, you can - you just can't call those functions from outside that partial file.

So, the trick is, call the function from the partial itself and output the result 'in-place'. Then simply include the partial in the EJS/HTML where you want to use the output in your HTML.

The two original commenters were correct all along (thank you ahwayakchih) - I just did not understand the answers at the time.

Since you cannot 'pass' arguments to the partial, you need to be working off 'globals' passed in from the render function.

When I get time, I will post a real world code example.

DanJHill
  • 167
  • 2
  • 12