Ext.XTemplate

1. template 是什么

template 是一个 HTML 片段的模板,它可以进行预编译从来提升性能。

2. Xtemplate

Xtemplate 继承自 template,Xtemplate 支持以下这些功能:

1.数组

1) 如果给定的是个数组,他会自动填充,为数组总每一项重复 template 中的 block。
2) for=“.” ,会从根节点开始重复,for=“record” ,会从 record 节点开始重复。

'<tpl for="score" >' +
'<span class="values"></span>' +
'</tpl>' +
例如,数组score,其中每一个值为values。

2.处理基本的比较运算符

注:大于和小于号要使用html实体字符。

'<tpl if="price &amp;&amp; discount">' +

'<div class="item-price"><span>{price}</span><span>{discount}</span></div>' +

'</tpl>'

例如,price && discount 为true时,显示div。

3.支持基本的数学函数

支持+ - * /等

<span class="report-blue-number">{[parseInt((values.rightNum/values.totalNum).toFixed(2) * 100)]}%</span>
<span class="report-blue-number">{[values.totalNum-values.rightNum]}</span>

4.执行有内置模板变量的代码

任何在{[ ]}中的代码都会在 template 的作用域中被执行。生成的结果包括计算表达式和结果,其中代码中有一些特殊的变量如下:

  • out:template 附加的输出数组
  • values:当前作用域下的值,你可以通过改变作用域来改变子 template
  • parent:祖先的作用域
  • xindex:如果是循环 template,index 以 1 开始
  • xcont: 如果是循环 template,会循环 template 的所有的数据。


另外, 在 "{% ... %}"中的代码会被直接插入到 template 生成的代码中, 这些代码块没有输出,它们可以做一些简单的操作,例如,在循环中 break/continue,或者,控制构造函数或方法的调用(要求它们没有输出)。

5 自定义成员函数

自定义函数需要写在 Xtemplate 内部,写在html代码之后,用逗号隔开。

tpl: new Ext.XTemplate(
html code,
{
starClass: function (values) {},
isPassed: function (defeatNum) {}
}
)

html行间属性调用该函数时使用class=“this.startClass(vaules)”,内容显示时{variable},函数输出内容时{[fu]}。

'<p class="this.setPriceCls(values.transaction_date)">{[Formatter.toFixed(values.price,1)]}</p>'
 

6 可以定义一些 API 中没有定义的特殊标记或内置运算符。

3.我遇到的问题及解决方法总结

3.1 我遇到的问题:


1)template 中出现空的 div 效果如图:


‘<div >’,
‘<tpl if = “entryType”=="money_fund"”>’,’<tpl>’,
‘</div >’,


原因:先声明了 DIV,后进行的判断,所以无论 IF 是否为真,都会有一个 DIV 块。
将 DIV 块放入 tpl 中即可,代码如下:


‘<tpl if = “entryType”=="money_fund"”>’,
‘<div >’, ‘</div >’,
’<tpl>’,


效果如下:
2)tpl 中断句时什么时候用“+”,什么时候用“,”
“+”:
没有“[]“时,断句要用“+”,如下:


tpl: '<div class="investment-portfolio-buysellpoint-head">' +
'</div>',


“,”:
有”[]“时,断句可以用“,”,如下:

itemTpl: [
'<div>',
'</div>'
],

3)设置tpl时,需要同时设置data,否则会造成数据不渲染。
4)使用tpl+data形式是,不是使用updateData方法,否则会造成数据不渲染。

3.2 总结:

1)参数的调用:
<tpl>{notifyingAt}</tpl>
其中:notifyingAt 为一个参数
参数可以做简单的四则样式,比如有一个 age 参数,我要算一算他 3 年以后是几岁的话:

<tpl>{age+3}</tpl>

2)函数的调用:

<tpl>{[Ext.Date.format(new Date(),"Y-m-d")]}</tpl>

3)函数中参数的调用:
<tpl>{[Ext.Date.format(value.notifyingAt,"Y-m-d")]}</tpl>

4)if else:

<tpl if="this.isBought(values.isBought)">
    // if
<tpl else>
    //else
</tpl>
原文地址:https://www.cnblogs.com/jun3101s/p/5823955.html