nodeJS + Swig template passing variable to javascript

谁说我不能喝 提交于 2019-12-12 10:46:12

问题


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!


回答1:


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.




回答2:


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

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



来源:https://stackoverflow.com/questions/18617065/nodejs-swig-template-passing-variable-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!