问题描述
假设我打开了一个浏览器,并在JavaScript中声明了一个全局变量。
Lets say I have a browser open, and in JavaScript I declare a global variable.
window.myGlobalVar = 'Hello!';
然后我为使用该变量的客户端渲染编译玉模板。
I then compile a jade template for client side rendering that uses that variable.
.foo= myGobalVar
我编译如下:
jade.compile('.foo= myGobalVar', {
client: true,
compileDebug: false
}).toString()
哪个产生这个模板功能:
Which yields this template function:
function anonymous(locals) {
var buf = [];
var locals_ = (locals || {}),
myGobalVar = locals_.myGobalVar;
jade.indent = [];
buf.push("\n<div class=\"foo\">"
+ (jade.escape(null == (jade.interp = myGobalVar) ? "" : jade.interp))
+ "</div>");;
return buf.join("");
}
运行时会产生:
<div class="foo">undefined</div>
如你所见,jade编译器注意到我使用了一个变量,并通过 myGobalVar = locals_.myGobalVar;
强制它成为局部变量,它隐藏了我实际想要使用的全局变量。
As you can see, the jade compiler notices that I used a variable, and forces it to be a local variable via myGobalVar = locals_.myGobalVar;
, which shadows the global variable I actually want to use.
所以我尝试引用 window.myGlobalVar
和jade然后只是阴影窗口
。
So I tried referencing window.myGlobalVar
and jade then just shadowed window
.
为什么不传递我想要使用的每个全局?那么在运行时我不确定需要什么全局变量。我有几十个全局构造函数并且明确地将它们全部传递将需要相当重构。
Why not just pass in every global I want to use? Well at runtime I'm not sure what globals are necessary. I have dozens of global constructors and passing them all in explicitly will require quite the refactoring.
那么如何以允许引用的方式编译客户端jade模板到glbal varaibles?
So how do I get a client side jade template compiled in a way that allows references to glbal varaibles?
更新:
我做了排序成功的。
for (key in window) {
if (localsObject[key] == null)
localsObject[key] = window[key];
}
}
renderTemplate(localsObject);
但该死的确让我觉得很脏......当然有更好的方法吗?
But god damn does that make me feel dirty... Surely there is a better way?
推荐答案
您可以将要在jade模板中使用的全局变量的名称与options函数的options对象一起传递。请参阅jade api docs:
You can pass the names of the globals, you want to use in jade templates, with the options object to the compile function. See jade api docs: http://jade-lang.com/api/
jade.compile(template, { globals: ['globalone','globaltwo']})
看到这个小提琴看到它的实际效果:
See this fiddle to see it in action: http://jsfiddle.net/lchngr/J5WJb/5/
这篇关于Jade模板如何使用客户端全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!