Search code examples
listsencha-touchsencha-touch-2itemtemplate

Set image in itemTpl dynamically in Sencha Touch List


I have to set an image with text in a row of my List. But image is to be chosen at runtime.

Here is my Store:

Ext.define('MyApp.model.Sample', {
           extend: 'Ext.data.Model',

           config: {
           fields: [ 
                    { name: 'uName', mapping: '@name' },
                    { name: 'uId', mapping: '@id' }
                    ]
                }
           });

In my list itemTpl, I am able to display uName, and i have created a function(getImageURL) that is suppose to return the required image, so how shall i use or what is the way/syntax of using uId from the above ( which has a value of either 0 or 1)

And here is my list:

  itemTpl : new Ext.XTemplate("<img src=\"{[this.getImageURL()]}\" width=\"20\" height=\"20\"></img><span>    {uName}</span>",
              {
               getImageURL : function()
                {

                // I have to return either of two images
                // if  uId = 0, return 'resources/images/Image0.png'
                // if uId = 1, return 'resources/images/Image1.png'

                }
              }
    ),

Solution

  • You don't need to use a function. XTemplate provide if and else statements.

    Take a look at it here

    Example

    var tpl = new Ext.XTemplate(
        '<p>Name: {name}</p>',
        '<p>Kids: ',
        '<tpl for="kids">',
            '<p>{name} is a ',
            '<tpl if="age &gt;= 13">',
                '<p>teenager</p>',
            '<tpl elseif="age &gt;= 2">',
                '<p>kid</p>',
            '<tpl else>',
                '<p>baby</p>',
            '</tpl>',
        '</tpl></p>'
    );
    

    Hope this helps