mde / ejs

Embedded JavaScript templates -- http://ejs.co
Apache License 2.0
7.71k stars 846 forks source link

EJS on client side, on a EJS page which is itself rendered on server #648

Closed ghost closed 2 years ago

ghost commented 2 years ago

I have a page rendered on server, but for one part, I want to deal with data on client (doing asynchronous browser fetches).

Having the page index.ejs containing:


<% if(typeof(title) != 'undefined' && title === 'Reactivate') { %> // this is some data rendered correctly on server
// doing some stuff here
// The following script, should be copied as is, in other words the tag <%= %> must not be rendered on server
<script src="/unversioned_js/ejs.min.js"></script>
<script>
  {
    let people = ['geddy', 'neil', 'alex'];
    let html = ejs.render(`<%= people.join(", "); %>`, {people: people});
    console.log(html)
  }
</script>
</html>

So as you can guess already, I'm having an error people is not defined as this tag is evaluated on server already.

mde commented 2 years ago

Two possible solutions here. One is to keep your client-side EJS off the page, in a separate file — which is probably advisable anyhow. Or use a different delimiter either the client- or server-side evaluation, like @ or $ instead of %.

ghost commented 2 years ago

I checked the doc again, everything is there: <%%=

let people = ['geddy', 'neil', 'alex'];
let html = ejs.render(`<%%= people.join(", "); %>`, {people: people});
console.log(html)

Thanks a lot for you proposition I will think of separating files. May I suggest to add a hint on this in Client-side support section in docs ?.

Thanks

mde commented 2 years ago

The docs are part of the repo here, or on the EJS site repo: https://github.com/mde/ejs-site/ Feel free to submit a PR for this. I'd be happy to merge it.

ghost commented 2 years ago

I will tomorrow 💯