To transfer a variable from JavaScript to EJS, you can pass it as an object from your express route to your EJS file. Here is an example:
JavaScript:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const myVariable = 'Hello world!';
res.render('index.ejs', { myVariable: myVariable });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In the above code, we define the myVariable
variable inside our express route, and then pass it as an object to our EJS file via the res.render
method.
EJS:
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1><%= myVariable %></h1>
</body>
</html>
In the above EJS code, we use the <%= %>
tag to output the myVariable
that we passed to the EJS file. This will generate HTML that looks like this:
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
Note that we could have named the variable in our EJS file anything we want, as long as we reference it correctly. For example, we could have passed it like this: { message: myVariable }
, and then referenced it in our EJS file like this: <%= message %>
.
Asked: 2022-03-11 11:00:00 +0000
Seen: 21 times
Last updated: Feb 23 '23