mackenir
mackenir

Reputation: 10969

Is there a cleaner way to propagate attached data to nested templates?

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?

Upvotes: 1

Views: 70

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

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/

Upvotes: 1

Related Questions