如何将变量从玉模板文件传递给Javascript文件? [英] How do I pass variable from a Jade template file to a Javascript file?
问题描述
我的server.js文件中有这行代码
res.render(aws.jade,{data:JSON.stringify({'val':'This is a Test'})});
基本上我只是试图获取数据中的值到aws.jade模板文件
这是aws.jade
html
头
脚本(type ='text / javascript')
var data =!{data}
link(rel ='stylesheet',href ='/ stylesheets / style.css'
body
title标题
h1标题
#div.test
我在Firebug控制台中收到此错误:
< var> data = {val:这是一个测试}< / var>
有人可以解释为什么会发生这种情况,并让我从玉中传递变量模板文件到JS文件?
谢谢
尝试在脚本之后添加一个。
字符,这告诉Jade你想要一个标签内的一个文本块。
这是您更新的代码。
html
头
脚本(type ='text / javascript')。
var data =!{data}
link(rel ='stylesheet',href ='/ stylesheets / style.css')
body
title标题
h1标题
#div.test
编辑 - 设置title.val
首先,您应该更改响应,删除JSON.stringify,以便返回一个不是字符串值的对象。
res.render(aws.jade,{data:{'val':'This is a Test'}});
然后,您应该能够使用点符号直接访问数据对象的属性和结构,并分配直接到这样的标题元素...
title = data.val
Im very new to Node.js and trying to get my head round few things.How do I pass variable from a Jade template file to a JS file?
I have got this line of code in my server.js file
res.render("aws.jade", {data : JSON.stringify({'val' : 'This is a Test'})});
Basically Im just trying to get values in data to aws.jade template file
And this is aws.jade
html
head
script(type='text/javascript')
var data = !{data}
link(rel='stylesheet', href='/stylesheets/style.css')
body
title Title
h1 Heading
#div.test
I keep getting this error in the Firebug console:
<var>data = {"val":"This is a Test"}</var>
Could someone please explain as to why this is happening and a way for me to pass variable from a Jade template file to a JS file?
Thank You
Try adding a .
character after the script, this tells Jade that you want a block of text inside a tag.
Here's your updated code.
html
head
script(type='text/javascript').
var data = !{data}
link(rel='stylesheet', href='/stylesheets/style.css')
body
title Title
h1 Heading
#div.test
EDIT - To set title to data.val
First you should change your response, remove JSON.stringify so you're returning an object not a string value.
res.render("aws.jade", {data : {'val' : 'This is a Test'}});
Then you should be able to access the data objects attributes and structure directly using dot notation, and assign it straight to the title element like this...
title= data.val
这篇关于如何将变量从玉模板文件传递给Javascript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!