Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zd-project opened this issue May 29, 2019 · 2 comments

Comments

@zd-project
Copy link

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 zd-project changed the title What is the correct way to refactor ejs helper functions to separate files? What is the correct way to refactor ejs helper functions to separate files (w/ Express)? May 29, 2019
@zd-project
Copy link
Author

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.

@mde
Copy link
Owner

mde commented May 30, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants