Is there a cleaner way to propagate attached data to nested templates?
To make some 'global values' av开发者_开发知识库ailable 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 TemplateGlobals
or similar namespace:
Globals = {};
Globals.TemplateProperties = {};
Globals.TemplateProperties.TestProperty = "Test";
Now there's no need to pass around the globals
object 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.
${Globals.TemplateProperties.TestProperty}
Example: http://jsfiddle.net/andrewwhitaker/CqVxS/
精彩评论