简体   繁体   中英

How to pass a Javascript variable to an EJS object as a parameter?

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

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?

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] %>"  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM