ExtJS xtemplate Example

Problem

You want to use an html template within client-side ExtJS code.

Tested in ExtJS Version

4.1.1

Screenshot

Solution
Use ExtJS’s xtemplates.

 Ext.onReady(function() {
  var trackStore = new Ext.data.Store({
    storeId: 'soundCloudStore',
    proxy: {
      type: 'ajax',
      url: 'blues.json',
      reader: {
        type: 'json',
        idProperty: 'id'
      }
    },
    fields:['duration', 'genre', 'created_at', 'kind', 'title', 'id']
  });
  trackStore.load(
    function(records, operations, successful) { 
      var panel =  Ext.create('Ext.panel.Panel', {
        title: 'Tracks',
        store: trackStore,
        height: 190,
        width: 550,
        renderTo: Ext.getBody()
  });
 
  var tpl = new Ext.XTemplate(
    '<tpl for=".">',
      '<tpl for="data">',
      '<b>Title:</b> {title}',
        '<tpl if="genre != &quot;&quot;">',		  '
      '<b>Genre:</b> {genre}',
        '</tpl>',
        '<tpl if="duration &gt; 1">',
           '<b>Duration:</b> {duration}',
        '</tpl>',
      '</tpl>',
    '</tpl>'
  );
  tpl.overwrite(panel.body, records);
 
  });
})
]]>

Discussion

A popular alternative to ExtJS templates is eJS:
http://embeddedjs.com/

See also the ExtJS ToolTips for an example of where this could be used, and the ExtJS ListView example to see another rendition of the same data..

 

3 Replies to “ExtJS xtemplate Example”

  1. Hi Gary, thanks for your exmaple. Have you any idea how to use a {x} variable inside a function in this template. for example this code is not working :
    ‘ {[new Date({timestamp} + 1000*3600)]} ‘

    but :
    ‘ {[new Date(132502 + 1000*3600)]} ‘ is fine.

  2. How would you write this in an ExtJs 4.2 MVC application? How to seperate the controller, model and view parts? Xtemplate falls in view or controller?

    Thank you in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *