byrdr
byrdr

Reputation: 5467

Storing Express data in global variable through view

I have a data object "bootstrappedUser" being passed into the view through a route.

app.get('/', function(req, res) {
    res.render('index.ejs',{
      bootstrappedUser: req.user,
      page: 'rest'
    });
});

I'd like to store the "bootstrappedUser" JSON object into a global variable and use that variable to keep persistent login. Currently the window.bootstrappedUserObject is being accessed when bootstrappedUser is defined but it is not being set to anything.

 <% if (bootstrappedUser!= undefined) { %>
  <script>
  window.bootstrappedUserObject = <% bootstrappedUser %>                
</script>
<% } %> 

I am receiving the following source code on login

<script>
window.bootstrappedUserObject =                                        
  </script>

Upvotes: 0

Views: 198

Answers (1)

go-oleg
go-oleg

Reputation: 19480

You want to use <%= %> instead of <% %>:

 <% if (bootstrappedUser!= undefined) { %>
  <script>
  window.bootstrappedUserObject = <%= bootstrappedUser %>                
</script>
<% } %> 

<% %> just evaluates JavaScript whereas <%= %> interpolates the result of an expression into your template.

Upvotes: 1

Related Questions