To make some ‘global values’ available in my template, I specify the ‘options’ parameter when calling tmpl:
var globals = { aProperty: "foo" };
$("#tcontent").tmpl(data,
{ globals: globals }) // <-- options
.appendTo("#content");
I can then access properties of globals like this:
${$item.globals.aProperty}
Then, whenever I call another template from within the template, I need to do the following, to ensure that globals is once more available in the nested template:
{{tmpl(nestedValue, {globals: $item.globals} ) "#tnestedtemplate"}}
This is kind of fiddly. Is there some other cleaner mechanism for making these global values accessible in my templates?
If you’re namespacing your JavaScript, you could add a
TemplateGlobalsor similar namespace:Now there’s no need to pass around the
globalsobject when you call.tmpl. You can access the properties directly. The obvious downside to this is that now these properties are available to all of your JS code.Example: http://jsfiddle.net/andrewwhitaker/CqVxS/