1

I have a question, is it possible to define a variable in nodejs and then use it in the ejs page? So for example var newOne = "Yes" in nodejs. And then i want to use this variable in the ejs page to check if that variable is equal to yes, in its script tag. I tried this but it always ends up as undefined variable.

How does one do this?

1 Answer 1

1

Yes you can do that. Suppose you have a variable in node

var newOne = "Yes";

you can use the variable in ejs, like the following.

  1. You need to send the variable into the view during the rendering like below
res.render('/nameOfTheRoute', {
  newOneInView : newOne
});
  1. Then you can check conditions in ejs by accessing newOneInView like below
<%if (newOneInView == "Yes") { %>
// Do something
<% } %>
Sign up to request clarification or add additional context in comments.

7 Comments

Quick other question @arulmani venkatesh is there also a way to do this reverse? So that i would set up a variable in the ejs file and use it in nodejs?
Thanks, one more question @arulmani venkatesh how do i make this script run when the page is loading in. Because right now its seems that it wont run by it self.
ejs scripts are initiated by page load. So this shld work when the page is called in
And what if would want to change the variable value from the client side ? @arulmani venkatesh
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.