rnjai
rnjai

Reputation: 1135

Set view variables in ExpressJS from JavaScript

Let's say I pass a variable myvar from my router to the view-

app.get('/test', function(req, res) {
    res.render('testPage', {
        myVar: true
    });
}

Now I can use this variable in the view within script tag like this -

<script>
  var myVar = <%- JSON.stringify(myVar) %>;
  console.log(myVar); // prints 'true'
</script>

What I want to do is reset the view variable myVar to false however that isn't happening.

<script>
  var myVarJS = <%- JSON.stringify(myVar) %>;
  console.log(myVarJS); // prints 'true'
  <%- myVar = false %>;
  myVarJS = <%- JSON.stringify(myVar) %>;
  console.log(myVarJS); // still prints 'true'
</script>

The scenario is that one can pass view variables from the router with a value. Now I would like to change the value of that variable from my client side javascript.

The templating engine for views that I am using is EJS.

Upvotes: 1

Views: 425

Answers (1)

trex005
trex005

Reputation: 5115

Change <%- myVar = false %>; to <% myVar = false %>;

Upvotes: 1

Related Questions