ExtJs的XTemplate使用

  ExtJs目前还是很多企业web应用首选的js框架,ext本身提供了很多很好的控件给我们使用了,简单的应用已经能基本满足要求,但是,当我们深度使用Ext后,为了应对一些奇怪的需求,就要使用到一些Ext的秘笈了,其中一个就是XTemplate。什么?你还不知道XTemplate是个什么东西?好吧,let go!

 

  •   先介绍一下XTemplate

 

 

 

HIERARCHY

Ext.Template
Ext.XTemplate

 

 

XTemplate是Template的一个子类,他能做什么呢?请看docs里面的描述:

A template class that supports advanced functionality like:

  • Autofilling arrays using templates and sub-templates
  • Conditional processing with basic comparison operators
  • Basic math function support
  • Execute arbitrary inline code with special built-in template variables
  • Custom member functions
  • Many special tags and built-in operators that aren't defined as part of the API, but are supported in the templates that can be created
  上面的意思就是说,XTemplate就是个模板类,模板是什么?就是结合数据动态生成页面(html)的工具:模板+数据 = HTML。上面还提到这个模板类支持的功能,包括:支持数组的输出、支持条件判断、支持基础的数学运算、支持内建的模板变量....等等

  •   XTemplate的用法

  知道XTemplate是什么之后,我们来看看怎么来使用他吧

 

先准备例子数据:

 

 

var data = {
name: 'Tommy Maintz',
title: 'Lead Developer',
company: 'Sencha Inc.',
email: '[email protected]',
address: '5 Cups Drive',
city: 'Palo Alto',
state: 'CA',
zip: '44102',
drinks: ['Coffee', 'Soda', 'Water'],
kids: [{
        name: 'Joshua',
        age:3
    },{
        name: 'Matthew',
        age:2
    },{
        name: 'Solomon',
        age:0
}]
};

 

 

数组处理

 

 

var tpl = new Ext.XTemplate(
    '<p>Kids: ',
    '<tpl for=".">',       // process the data.kids node
        '<p>{#}. {name}</p>',  // use current array index to autonumber
    '</tpl></p>'
);
tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
 

 

 上面就是单独使用XTemplate的过程。

 

 

条件判断

 

The tpl tag and the if operator are used to provide conditional checks for deciding whether or not to render specific parts of the template. Notes:

  • Double quotes must be encoded if used within the conditional
  • There is no else operator — if needed, two opposite if statements should be used.
<tpl if="age > 1 && age < 10">Child</tpl>
<tpl if="age >= 10 && age < 18">Teenager</tpl>
<tpl if="this.isGirl(name)">...</tpl>
<tpl if="id==\'download\'">...</tpl>
<tpl if="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl>
// no good:
<tpl if="name == "Tommy"">Hello</tpl>
// encode " if it is part of the condition, e.g.
<tpl if="name == &quot;Tommy&quot;">Hello</tpl>

Using the sample data above:

var tpl = new Ext.XTemplate(
   
'<p>Name: {name}</p>',
   
'<p>Kids: ',
   
'<tpl for="kids">',
       
'<tpl if="age &gt; 1">',
           
'<p>{name}</p>',
       
'</tpl>',
   
'</tpl></p>'
);
tpl
.overwrite(panel.body, data);
 

基本数学运算

 

 

  • The following basic math operators may be applied directly on numeric data values:

    + - * /
    For example:
    var tpl = new Ext.XTemplate(
       
    '<p>Name: {name}</p>',
       
    '<p>Kids: ',
       
    '<tpl for="kids">',
           
    '<tpl if="age &gt; 1">',  // <-- Note that the > is encoded
               
    '<p>{#}: {name}</p>',  // <-- Auto-number each item
               
    '<p>In 5 Years: {age+5}</p>',  // <-- Basic math
               
    '<p>Dad: {parent.name}</p>',
           
    '</tpl>',
       
    '</tpl></p>'
    );
    tpl
    .overwrite(panel.body, data);
     

 

 


 

 

使用内建的模板变量

 

 

Anything between {[ ... ]} is considered code to be executed in the scope of the template. There are some special variables available in that code:

  • values: The values in the current scope. If you are using scope changing sub-templates, you can change what values is.
  • parent: The scope (values) of the ancestor template.
  • xindex: If you are in a looping template, the index of the loop you are in (1-based).
  • xcount: If you are in a looping template, the total length of the array you are looping.

This example demonstrates basic row striping using an inline code block and the xindex variable:

 

var tpl = new Ext.XTemplate(
   
'<p>Name: {name}</p>',
   
'<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
   
'<p>Kids: ',
   
'<tpl for="kids">',
       
'<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
       
'{name}',
       
'</div>',
   
'</tpl></p>'
 
);
tpl
.overwrite(panel.body, data);

使用自定义函数

 

 

 

  • One or more member functions can be specified in a configuration object passed into the XTemplate constructor for more complex processing:

    var tpl = new Ext.XTemplate(
       
    '<p>Name: {name}</p>',
       
    '<p>Kids: ',
       
    '<tpl for="kids">',
           
    '<tpl if="this.isGirl(name)">',
               
    '<p>Girl: {name} - {age}</p>',
           
    '</tpl>',
             
    // use opposite if statement to simulate 'else' processing:
           
    '<tpl if="this.isGirl(name) == false">',
               
    '<p>Boy: {name} - {age}</p>',
           
    '</tpl>',
           
    '<tpl if="this.isBaby(age)">',
               
    '<p>{name} is a baby!</p>',
           
    '</tpl>',
       
    '</tpl></p>',
       
    {
           
    // XTemplate configuration:
            compiled
    : true,
           
    // member functions:
            isGirl
    : function(name){
               
    return name == 'Sara Grace';
           
    },
            isBaby
    : function(age){
               
    return age < 1;
           
    }
       
    }
    );
    tpl
    .overwrite(panel.body, data);
     

  • 结合控件使用XTemplate

XTemplate在以下的控件中都实现了Xtemplate的用法:

例如用于分组Grid中的自定义Group列头

Sample usage:

var grid = new Ext.grid.GridPanel({ // A groupingStore is required for a GroupingView store: new Ext.data.GroupingStore({ autoDestroy: true, reader: reader, data: xg.dummyData, sortInfo: {field: 'company', direction: 'ASC'}, groupOnSort: true, remoteGroup: true, groupField: 'industry' }), colModel: new Ext.grid.ColumnModel({ columns:[ {id:'company',header: 'Company', width: 60, dataIndex: 'company'}, // groupable, groupName, groupRender are also configurable at column level {header: 'Price', renderer: Ext.util.Format.usMoney, dataIndex: 'price', groupable: false}, {header: 'Change', dataIndex: 'change', renderer: Ext.util.Format.usMoney}, {header: 'Industry', dataIndex: 'industry'}, {header: 'Last Updated', renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'} ], defaults: { sortable: true, menuDisabled: false, width: 20 } }), view: new Ext.grid.GroupingView({ forceFit: true, // custom grouping text template to display the number of items per group groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})' }), frame:true, width: 700, height: 450, collapsible: true, animCollapse: false, title: 'Grouping Example', iconCls: 'icon-grid', renderTo: document.body });

 

你可能感兴趣的:(template)