Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS + Swig template passing variable to javascript

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!

like image 214
mathmonkey Avatar asked Sep 04 '13 14:09

mathmonkey


2 Answers

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.

like image 179
Wilson Avatar answered Sep 19 '22 13:09

Wilson


To pass json objects from backend server to the template you can do:

var data = {{jsonData|raw|json}}

like image 33
ycode Avatar answered Sep 19 '22 13:09

ycode