您需要使用unescaped string interpolation和字符串化将您的pug变量转换为客户端浏览器变量:
我知道我可以像这样通过模板从服务器传递变量:
//- template.pug
p #{name}'s Pug source code!
并这样打电话
pug.renderFile('template.pug', {
name: 'Timothy'
})
(从their landing page抄袭/粘贴)>
但是我想传递“更复杂的”变量,例如,我的哈巴狗来源中可能包含]]
script. window.foo = !{foo};
并且我想传递对象列表:
foo = [{one: 1}, {two: 2}, {three: 3}]; pug.renderFile('template.pug', { foo });
但是会产生
<script> window.foo = [[Object object], [Object object
依此类推。看起来像哈巴狗(或管道中的东西)在输入上调用“ toString”。
我尝试使用JSON字符串化作为Kyle Gillen helpfully answers here来修复它,所以我写了这个:
script. window.foo = JSON.parse('!{JSON.stringify(foo)}');
但是我的
foo
变量实际上包含很多'
单撇号字符,因此也会出现此错误。并且用"
双引号引起来是令人讨厌的,因为JSON.stringify
当然会产生带双引号的JSON。我已经尝试将每个
'
都转义为>]script. window.foo = JSON.parse('!{JSON.stringify(foo).replace(/'/, "\\'")}');
但是这一直不一致。我认为字符串化中还有其他字符或怪异现象会导致字符串尽早结束,每次迭代尝试更正先前的字符时,我都会遇到不同的错误。
这就是为什么我想问这个问题,因为我敢肯定必须有一个更简单更好的方法。
如何通过帕格从服务器向客户端安全地传递完全相同的变量?
我知道我可以像这样通过模板将变量从服务器传递://-template.pug p#{name}的Pug源代码!并这样调用pug.renderFile('template.pug',{名称:'Timothy'...
您需要使用unescaped string interpolation和字符串化将您的pug变量转换为客户端浏览器变量:
var arrayOnClient = !{JSON.stringify(arrayOnServer)};
如果express / pug中的变量为
['a', 'b', 'c']
,则将输出:
var arrayOnClient = ['a', 'b', 'c'];
没有字符串化,您将得到类似这样的内容,因为它不是有效的JavaScript,只会在浏览器中引发错误:
var arrayOnClient = [Object object];
您需要使用unescaped string interpolation和字符串化将您的pug变量转换为客户端浏览器变量: