How can a Jade template use client-side global variables?

Suppose I have a browser open, and in JavaScript I declare a global variable.

window.myGlobalVar = 'Hello!'; 

Then I compile a jade template for client-side rendering that uses this variable.

 .foo= myGobalVar 

What I compile like this:

 jade.compile('.foo= myGobalVar', { client: true, compileDebug: false }).toString() 

What this template function gives is:

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

What on startup will produce:

 <div class="foo">undefined</div> 

As you can see, the jade compiler notices that I used the variable and makes it be a local variable via myGobalVar = locals_.myGobalVar; which hides the global variable that I really want to use.

So, I tried the window.myGlobalVar and jade link, then the window just shaded.

Why not just go through every global that I want to use? Well, at runtime, I'm not sure what global changes are needed. I have dozens of global constructors, and passing them explicitly will require quite a bit of refactoring.

So, how do I get the client-side jade template compiled in a way that allows glbal varaibles to be referenced?


Update:

I managed to handle it.

 for (key in window) { if (localsObject[key] == null) localsObject[key] = window[key]; } } renderTemplate(localsObject); 

But hell, it makes me feel dirty ... Sure, is there a better way?

+6
source share
1 answer

You can pass the names of global characters that you want to use in jade patterns with the options object for the compilation function. See Jade api docs: http://jade-lang.com/api/

 jade.compile(template, { globals: ['globalone','globaltwo']}) 

Take a look at this script to see it in action: http://jsfiddle.net/lchngr/J5WJb/5/

+2
source

Source: https://habr.com/ru/post/948982/


All Articles