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..

 

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

3 replies
  1. Sara
    Sara says:

    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.

    Reply
  2. kumar
    kumar says:

    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.

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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