nodeJS + Swig模板将变量传递给javascript [英] nodeJS + Swig template passing variable to javascript

查看:95
本文介绍了nodeJS + Swig模板将变量传递给javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用express + swig模板让nodeJS从服务器端向客户端javascript传递变量?我知道可以在Jade中完成,但是我宁愿使用更类似于HTML的模板引擎.感谢您的帮助!

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!

推荐答案

好的,我假设您可以使用consolidate.swig配置快递,否则请阅读此链接(

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});
});

然后在index.html文件中创建一个脚本标记:

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>

,然后在您的what.js文件中,可以使用用户名变量及其正确的值.希望对您有帮助.

and then in your whatever.js file the username variable will be available with its correct value. I hope that this help you.

这篇关于nodeJS + Swig模板将变量传递给javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆