Is there any way using express + swig template for nodeJS to pass variables from the server side to client side javascript? I know it can be done in Jade but I'd rather stick with a template engine that more closely resembles HTML. Thanks for the help guys!
OK I will assume that you could configure your express with consolidate.swig if not please read this link (http://tinyurl.com/kcs8kvy). Well I didn't find the direct way to pass variable values to client javascript but I have found a workaround.
for instance you're sending an object, in your route at express:
app.get("/", function(req, res){
var myUser = { name: "Obama" };
res.render("index", {user: myUser});
});
then in your index.html file you can create a script tag:
<html>
<body>
<script>
var username = "{{user.name}}";
</script>
<script src="whatever.js"></script>
</body>
</html>
and then in your whatever.js file the username variable will be available with its correct value. I hope that this help you.
To pass json objects from backend server to the template you can do:
var data = {{jsonData|raw|json}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With