Angry B Angry B -3 years ago 86
Javascript Question

Handlebars variable working when it placed on index.hbs page, but isn't working, when I connect it with <script>

In my controller I set

myId
variavle:

router.get('/', function(req, res, next) {
res.render('index',{
myId: req.user._id,
});
});


When I am trying to use it in index.hbs:

<script>
alert("{{myId}}"); //58f560395ff25d09fc382448 (works fine)
</script>


But when I am connecting script from my scripts folder:

<script src="public/js/script.js"></script>


And in my script.js file trying to:

alert("{{myId}}") // {{myId}} (works bad);


It shows me string "myId", how can I use handlebars variables in connected files?

Answer Source

Because express/handlebars only parses your index.hbs and not your script file.

What you can do though is setting a variable in the global scope inside your index.hbs and later use that global variable in your script files, like so:

Your index.hbs:

<body>
  // your html
  <script>
    var myId = "{{ myId }}";
  </script>
  <script src="script.js"></script>
</body>

Your script.js:

alert( myId );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download