Applying Templates

This article describes a few techniques for rendering templates.

The simplest I have found is to use apply and call then call update for your component and pass in the HTML that apply provided to you.

For example, in a panel, I may have the followin code:

function renderTemplate(record) {
   var data = record.data,
       html = this.sectionsTemplate.apply(sections);

   this.update(html);
}

Helper Functions

You can define and pass helper functions when you declare an XTemplate by putting the helper functions in an object at the end of the declaration. They can then be called using the stardard {[this.myfunc(values)]} syntax. Note that in this scope

    processedRowTemplate: new Ext.XTemplate(
        '<tr class="{cls}">',
            '<td>',
                '{label}: ',
                '{[this.formatCount(values.count)]} ',
            '</td>',
        '</tr>',
        {
            formatCount: function (value) {
                var count,
                    results = value;
                if (value) {
                    count = parseInt(value, 0);
                    results = Ext.util.Format.number(count, '0,0');
                }
                return results;
            }
        }
    ),

Sub-Templates

You can render sub-templates using a helper function that calls another template. Getting a reference to your template is left as an exercise for you. Easy options are to include it in the data you are using, or create static templates.

The example below includes a template definition inside the data that gets passed to the root template

data = [
  {
    sectionCls: 'section1',    
    rowTemplate: new Ext.XTemplate(...),
    rows: [
      ...
    ]
  }
]

The main template calls the sub-template for each sub-array object it processed:

template = new Ext.XTemplate(
    '<tpl for=".">',    
        '<table class="{sectionCls}">',
            '<tpl for="rows">',
                '{[this.template(parent.rowTemplate, values)]}',
            '</tpl>',
        '</table>',
    '</tpl>',
    {
        template: function (tpl, values) {
            return tpl.apply(values);
        },
    }
),