mathmonkey
mathmonkey

Reputation: 335

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!

Upvotes: 6

Views: 4287

Answers (2)

ycode
ycode

Reputation: 301

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

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

Upvotes: 2

Wilson
Wilson

Reputation: 9136

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.

Upvotes: 11

Related Questions