Reputation: 904
I am using express js and rendering an file using
res.render('plain',{state:'admin'})
where plain.ejs is an ejs file. This file has an include main.js
<script src ="/main.js"></script>
How can i access the state variable in the main.js file ,please help !!!
Upvotes: 3
Views: 3279
Reputation: 4443
You can't directly. But you can do something like this :
plain.ejs
<script>
var state = {{ state }};
</script>
<script src ="/main.js"></script>
then in main.js
console.log(state);
Upvotes: 2
Reputation: 2739
Possibly dirty solution but you could create the state variable in global scope and main.js will be able to access it:
<script type='text/javascript'>
var state = '<%= state%>'
</script>
<script src ="/main.js"></script>
If you have more data to be passed to the client you could pass it as an object:
res.render('plain',{data: {state:'admin', page_title: 'first page'}})
And then just output the whole object like this:
<script type='text/javascript'>
var data = <%= JSON.stringify(data)%>
</script>
This way you could access the state as by data.state
.
Upvotes: 0