ejs icon indicating copy to clipboard operation
ejs copied to clipboard

What is the correct way to refactor ejs helper functions to separate files (w/ Express)?

Open zd-project opened this issue 5 years ago • 2 comments

I've been looking into this issue and found #111 #352 to be relevant posts. Basically I wrote up a few helper functions for rendering and found them frequently used across many templates, so I want to refactor them out to, say, utils.js (or ejs)

I know I can include them through express but I also want to organize my helper function files close to view templates, as their logic concerns UI purely. Passing back and forth through express means I need to reference files across directories, which only complicates things.

I tried using include method but that seems not to be importing functions correctly.

I'm wondering what is the correct way to do so. If there're already discussions about this please refer me to it, thanks.

zd-project avatar May 29 '19 01:05 zd-project

Looks like the include function is simply evaluate and output the result string from another file. I guess it's possible to do

<% eval(include('...')) %>

This looks a bit hacky, an obviously inefficient. I'm wondering if there's a better way to do it.

I also found out, weirdly, that dynamic import statement is supported, though I don't know how to enable async functionality when ejs is used as view engine for express.

zd-project avatar May 29 '19 20:05 zd-project

It makes sense that import works, since EJS is just evaluating JavaScript. I'm not entirely clear what it is you're trying to do — EJS is really just for rendering, and shouldn't include a lot of extra logic. Is there some specific reason you can't pass your helper functions into the render function as locals?

let helpers = {
  foo: (str) => { return str + ' foo'; }
};
ejs.render('<%=.helpers.foo("howdy"); %>' {helpers: helpers});

We have been thinking about an EJS v3 that assumes all I/O to be async, and allows async rendering, and have done some of the groundwork for that, but that is not happening immediately.

mde avatar May 30 '19 03:05 mde