Ask Your Question
2

How to transfer a variable from JavaScript to EJS?

asked 2022-03-11 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-02-23 01:00:00 +0000

devzero gravatar image

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 %>.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-11 11:00:00 +0000

Seen: 21 times

Last updated: Feb 23 '23