0

I am using EJS for the first time in my nodejs app and i need to use some template string inside EJS but i keep getting an error Below is a code snippet i was working on

<% const msg = `Hi i am interested in your product ${window.location.href}` %> 

In the above code i need to attach the current url to the string the assign it to the variable msg please help on how i can achieve this.

I have also tried using <%- %> delimiters. but it is still not working

Dijiflex
  • 523
  • 1
  • 8
  • 26
  • 1
    Why you are using `window.locatlion.href` on the server side (node.js)? Server side... you are supposed to know it already from the request itself. Your code seems to be a browser related javascript and not Node.js. – Yak O'Poe May 17 '20 at 10:38

1 Answers1

1

EJS renders the template on the server-side, so you don't have window object there.

Instead, you could get the URL from the server and pass it to the template.

For example with Express:

let url = req.protocol + "://" + req.get("host") + req.originalUrl;
res.render("index", { url });
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
  • Hi was trying to do this but failed ` <% const msg = `Hi i am interested in your product ${req.protocol + "://" + req.get("host") + req.originalUrl;} ` %> ` – Dijiflex May 18 '20 at 15:59
  • The text his i am interested ... is a string literal and is enclosed in with back ticks – Dijiflex May 18 '20 at 16:02
  • 1
    To do that you have to pass the `req` object when you are rendering the template (as seen above with the url), and use something like this: <% const msg = `Hi i am interested in your product ${req.protocol + "://" + req.get("host") + req.originalUrl}` %> – Tamas Szoke May 18 '20 at 16:09