问题
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
Which I compile like so:
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("");
}
Which when ran, would produce:
<div class="foo">undefined</div>
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.
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.
So how do I get a client side jade template compiled in a way that allows references to glbal varaibles?
Update:
I did sort of succeed with this.
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?
回答1:
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/
来源:https://stackoverflow.com/questions/17537049/how-can-a-jade-template-use-client-side-global-variables