0

I am trying to concatenate a Javascript variable to the EJS object to make it dynamic. Is there a way to do this with the EJS syntaxes or Javascript?

For example

Backend

res.render('webpage', {bookObj : bookObj})

Frontend

let author = "Shakespeare"
let book = "<%= bookObj['Shakespeare'] %>"  // <-- it works

let book = "<%= bookObj['" + author + "'] %>"  // <-- it does not work
ccmsd18
  • 58
  • 7

2 Answers2

0

You are confusing the server-side JavaScript in your EJS with the client-side JavaScript you are generating from it.

The string syntax outside the EJS tags is irrelevant to the JS inside it, and the variable you are using has to be declared in the same piece of software as you use it.

<% let author = "Shakespeare";  %>
let book = "<%= bookObj[author] %>" 

Of course, if the output contains special characters, it will break, so you are usually better off generating your JS literals by using a JSON encoder:

<% let author = "Shakespeare"; %>
let book = <%- JSON.stringify(bookObj[author]) %>;

See also What is the difference between client-side and server-side programming?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Same thing. It returns an error: "author is not defined" and does not render the page. But when I replace the author variable with the actual string value (e.g. 'Shakespeare') it returns the data without errors. – ccmsd18 Apr 04 '19 at 19:31
  • @ccmsd18 — It works fine when I test it: https://i.imgur.com/thFjr9A.png – Quentin Apr 04 '19 at 20:05
  • With your code, it worked for me too! Now could you tell me how would I change the author's value from a variable coming from an user input? `var userInput = document.getElementById(fieldID); <% let author = "Shakespeare"; %> let book = <%- JSON.stringify(bookObj[author]) %>;` – ccmsd18 Apr 04 '19 at 21:04
  • I refer you, again, to https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – Quentin Apr 04 '19 at 21:09
0

You need to define the variable within EJS context to get access in the server side code.

<% var author = "Shakespeare"; %>
let author = "<%= author %>";    
let book = "<%= bookObj[author] %>"  
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Yeah but that solution falls into the same problem. How would I change the author variable assigning a new value to it? – ccmsd18 Apr 04 '19 at 20:42
  • @ccmsd18 : actually the processed template id sending back to the client(browser) so it won't work as you expecting.... – Pranav C Balan Apr 05 '19 at 04:50