ExtJs2.0学习系列(11)--Ext.XTemplate
XTemplate是Extjs里面的模板组件.
下面我们看个最简单的例子.
效果图:
js代码:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->Ext.onReady(function(){
//数据源
vardata={
name:"博客园",
read:[{
book:'<<道不远人>>',
date:'2007-7-7'
},{
book:"<<大话设计模式>>",
date:"2006-6-6"
}]
}
//呈现组件
varmypanel=newExt.Panel({
width:400,
id:"mypanel",
title:"XtemplateData简单示例",
renderTo:Ext.getBody()
});
//创建模板
vartpl=newExt.XTemplate(
'<table><tr><th>名称:{name}</th></tr>',
'<tr><td>',
'<tplfor="read">',
'<p>编号:{#},书:{book},日期:{date}</p>',
'</tpl></td></tr></table>'
);
//重写绑定模板
tpl.overwrite(mypanel.body,data);
})
//数据源
vardata={
name:"博客园",
read:[{
book:'<<道不远人>>',
date:'2007-7-7'
},{
book:"<<大话设计模式>>",
date:"2006-6-6"
}]
}
//呈现组件
varmypanel=newExt.Panel({
width:400,
id:"mypanel",
title:"XtemplateData简单示例",
renderTo:Ext.getBody()
});
//创建模板
vartpl=newExt.XTemplate(
'<table><tr><th>名称:{name}</th></tr>',
'<tr><td>',
'<tplfor="read">',
'<p>编号:{#},书:{book},日期:{date}</p>',
'</tpl></td></tr></table>'
);
//重写绑定模板
tpl.overwrite(mypanel.body,data);
})
简要说明:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->/*
vartpl=newExt.XTemplate(
'<table><tr><th>名称:{name}</th></tr>',
'<tr><td>',
'<tplfor="read">',
'<p>编号:{#},书:{book},日期:{date}</p>',
'</tpl></td></tr></table>'
);
tpl.compile();
tpl.overwrite(mypanel.body,data);
*/
1.tpl.compile();//可以在创建模板后,添加tpl.compile();编译代码,速度快点.
2.tpl.overwrite(mypanel.body,data);//把数据填充到模板中去,并呈现到目标组件
3.名称:{name}//对于一维单数据对象,直接用{名称}输出,
4.,<tplfor="read">//对于多维对象(如拥有多条数据的表),使用tpl和for配合使用,会使用tpl的格式把数据一条一条输出,read为上级节点
5.{.}//对于一维对数据的对象,如color:['Red','Blue','Black'],可以用{.}按照tpl模板逐一输出,如:
'<tplfor="color">',
'<div>{.}</div>',
'</tpl>'
6.{#}//表示循环的索引
7.parent.***//在子对象中访问父对象元素,使用parent,如:{parent.name}
8.if//'<tplif="age>1">',
'<p>{name}</p>',
'</tpl>',
//if实现有条件的逻辑判断,很容易使用
9.其他几个常用的参数:
xindex//循环模板的当前索引index(从1开始),用[]。
xcount//循环模板循环的次数。用[]
举例:
'<tplfor="read">',
'<p>编号:{#},书:{book},日期:{date},奇偶:{[xindex%2==0?"偶数":"奇数"]},次数:{[xcount]}</p>',
'</tpl>
10.模板成员函数(借用api下):
vartpl=newExt.XTemplate(
'<tplfor="kids">',
'<tplif="this.isGirl(name)">',
'<p>Girl:{name}-{age}</p>',
'</tpl>',
'<tplif="this.isGirl(name)==false">',
'<p>Boy:{name}-{age}</p>',
'</tpl>',
'</tpl></p>',{
isGirl:function(name){
returnname=='SaraGrace';
},
isBaby:function(age){
returnage<1;
}
});
vartpl=newExt.XTemplate(
'<table><tr><th>名称:{name}</th></tr>',
'<tr><td>',
'<tplfor="read">',
'<p>编号:{#},书:{book},日期:{date}</p>',
'</tpl></td></tr></table>'
);
tpl.compile();
tpl.overwrite(mypanel.body,data);
*/
1.tpl.compile();//可以在创建模板后,添加tpl.compile();编译代码,速度快点.
2.tpl.overwrite(mypanel.body,data);//把数据填充到模板中去,并呈现到目标组件
3.名称:{name}//对于一维单数据对象,直接用{名称}输出,
4.,<tplfor="read">//对于多维对象(如拥有多条数据的表),使用tpl和for配合使用,会使用tpl的格式把数据一条一条输出,read为上级节点
5.{.}//对于一维对数据的对象,如color:['Red','Blue','Black'],可以用{.}按照tpl模板逐一输出,如:
'<tplfor="color">',
'<div>{.}</div>',
'</tpl>'
6.{#}//表示循环的索引
7.parent.***//在子对象中访问父对象元素,使用parent,如:{parent.name}
8.if//'<tplif="age>1">',
'<p>{name}</p>',
'</tpl>',
//if实现有条件的逻辑判断,很容易使用
9.其他几个常用的参数:
xindex//循环模板的当前索引index(从1开始),用[]。
xcount//循环模板循环的次数。用[]
举例:
'<tplfor="read">',
'<p>编号:{#},书:{book},日期:{date},奇偶:{[xindex%2==0?"偶数":"奇数"]},次数:{[xcount]}</p>',
'</tpl>
10.模板成员函数(借用api下):
vartpl=newExt.XTemplate(
'<tplfor="kids">',
'<tplif="this.isGirl(name)">',
'<p>Girl:{name}-{age}</p>',
'</tpl>',
'<tplif="this.isGirl(name)==false">',
'<p>Boy:{name}-{age}</p>',
'</tpl>',
'</tpl></p>',{
isGirl:function(name){
returnname=='SaraGrace';
},
isBaby:function(age){
returnage<1;
}
});
接下来,我们做个服务器的例子(好像很多朋友对这个要求很强烈啊)
实例演示:用模板呈现服务器数据
效果图:
html代码:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><divid="container">
</div>
</div>
css代码:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><styletype="text/css">
body
{
font-size:12px
}
#container
{
border:1pxsolidblack;
width:330px;
}
td,th
{
border-bottom:1pxdashedblack;
}
th
{
text-align:center;
}
.namewidth
{
width:120px;
}
.urlwidth
{
width:150px;
}
</style>
body
{
font-size:12px
}
#container
{
border:1pxsolidblack;
width:330px;
}
td,th
{
border-bottom:1pxdashedblack;
}
th
{
text-align:center;
}
.namewidth
{
width:120px;
}
.urlwidth
{
width:150px;
}
</style>
js代码:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->Ext.onReady(function(){
varmydata;
Ext.Ajax.request({
url:"getXtemplateData.ashx",//服务器端地址
success:function(request){
mydata=request.responseText;//服务器端文本数据
mydata=eval('('+mydata+')');//使用eval把文本数据转换为json对象
//或者用extjs自带的方法:mydata=Ext.util.JSON.decode(mydata),效果相同
vartpl2=newExt.XTemplate(
'<table><thead><tr><th> 编号</th><thclass="namewidth">名称</th>< thclass="urlwidth">地址</th><th>位置</th></tr>& lt;/thead><tbody>',
'<tplfor="results">',
'<tr><td>{#}</td><td>{linkname}</td><td>{linkurl}</td><td>{linkpos}</td><tr>',
'</tpl></tbody></table>'
);
tpl2.compile();
tpl2.overwrite(Ext.get("container"),mydata);
},
failure:function()
{
alert("failure!");
}
});
})
/***简单说明***
1.Ext.Ajax.request(),这里暂且对ajax不多谈论,后面会详细叙述
2.eval用"()"可以把规范文本转换为json对象,很重要!mydata=eval('('+mydata+')');
3.如果我们把模板创建和绑定放到ajax外面,会出错,因为ajax为异步调用,记住哦~
4.关于success函数的request参数,我截个图看看,就明白了
*/
varmydata;
Ext.Ajax.request({
url:"getXtemplateData.ashx",//服务器端地址
success:function(request){
mydata=request.responseText;//服务器端文本数据
mydata=eval('('+mydata+')');//使用eval把文本数据转换为json对象
//或者用extjs自带的方法:mydata=Ext.util.JSON.decode(mydata),效果相同
vartpl2=newExt.XTemplate(
'<table><thead><tr><th> 编号</th><thclass="namewidth">名称</th>< thclass="urlwidth">地址</th><th>位置</th></tr>& lt;/thead><tbody>',
'<tplfor="results">',
'<tr><td>{#}</td><td>{linkname}</td><td>{linkurl}</td><td>{linkpos}</td><tr>',
'</tpl></tbody></table>'
);
tpl2.compile();
tpl2.overwrite(Ext.get("container"),mydata);
},
failure:function()
{
alert("failure!");
}
});
})
/***简单说明***
1.Ext.Ajax.request(),这里暂且对ajax不多谈论,后面会详细叙述
2.eval用"()"可以把规范文本转换为json对象,很重要!mydata=eval('('+mydata+')');
3.如果我们把模板创建和绑定放到ajax外面,会出错,因为ajax为异步调用,记住哦~
4.关于success函数的request参数,我截个图看看,就明白了
*/
先看看数据库数据:
字段,数据都很清楚.下面是服务器getXtemplateData.ashx的代码:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><%@WebHandlerLanguage="C#"Class="getXtemplateData"%>
usingSystem;
usingSystem.Web;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Text;
publicclassgetXtemplateData:IHttpHandler{
publicvoidProcessRequest(HttpContextcontext){
StringBuildertempResult=newStringBuilder("{results:[");
stringconnstr=@"DataSource=WIN-7JW7UWR0M27/MSSQL2005;InitialCatalog=xgc;PersistSecurityInfo=True;UserID=sa;Password=************";
SqlConnectionsqlconn=newSqlConnection(connstr);
SqlCommandcomm=newSqlCommand("select*fromxLink",sqlconn);
sqlconn.Open();
SqlDataReadersdr=comm.ExecuteReader();
while(sdr.Read())
{
tempResult.Append("{id:'");
tempResult.Append((int)sdr["id"]);
tempResult.Append("',linkname:'");
tempResult.Append((string)sdr["linkname"]);
tempResult.Append("',linkurl:'");
tempResult.Append((string)sdr["linkurl"]);
tempResult.Append("',linkpos:");
tempResult.Append((int)sdr["linkpos"]);
tempResult.Append("},");
}
tempResult.Remove(tempResult.Length-1,1);//去掉多余的那个逗号
tempResult.Append("]}");
context.Response.Write(tempResult);//输出
}
publicboolIsReusable{
get{
returnfalse;
}
}
}
usingSystem;
usingSystem.Web;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Text;
publicclassgetXtemplateData:IHttpHandler{
publicvoidProcessRequest(HttpContextcontext){
StringBuildertempResult=newStringBuilder("{results:[");
stringconnstr=@"DataSource=WIN-7JW7UWR0M27/MSSQL2005;InitialCatalog=xgc;PersistSecurityInfo=True;UserID=sa;Password=************";
SqlConnectionsqlconn=newSqlConnection(connstr);
SqlCommandcomm=newSqlCommand("select*fromxLink",sqlconn);
sqlconn.Open();
SqlDataReadersdr=comm.ExecuteReader();
while(sdr.Read())
{
tempResult.Append("{id:'");
tempResult.Append((int)sdr["id"]);
tempResult.Append("',linkname:'");
tempResult.Append((string)sdr["linkname"]);
tempResult.Append("',linkurl:'");
tempResult.Append((string)sdr["linkurl"]);
tempResult.Append("',linkpos:");
tempResult.Append((int)sdr["linkpos"]);
tempResult.Append("},");
}
tempResult.Remove(tempResult.Length-1,1);//去掉多余的那个逗号
tempResult.Append("]}");
context.Response.Write(tempResult);//输出
}
publicboolIsReusable{
get{
returnfalse;
}
}
}
今天对XTemplate做了个简单介绍,下篇我们开始TreePanel的学习讨论~!
最后推荐个网站:***视频网 ,谢谢支持!
============补充==========
我们在上面对基础上作个查询:
html代码为:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><divid="head"><inputid="linkid"type="text"/></div>
<divid="container">
</div>
<divid="container">
</div>
js代码在上面js的基础上添加下面部分:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->newExt.Button({
text:"查询大于指定id值的记录",
handler:function(){
Ext.Ajax.request({
url:"getXtemplateData.ashx?id="+Ext.get("linkid").dom.value,//获取文本框的值
success:function(request){
mydata=request.responseText;
mydata=eval('('+mydata+')');
tpl2.overwrite(Ext.get("container"),mydata);
},
failure:function()
{
alert("failure!");
}
});
}
}).render(document.body,"head");
text:"查询大于指定id值的记录",
handler:function(){
Ext.Ajax.request({
url:"getXtemplateData.ashx?id="+Ext.get("linkid").dom.value,//获取文本框的值
success:function(request){
mydata=request.responseText;
mydata=eval('('+mydata+')');
tpl2.overwrite(Ext.get("container"),mydata);
},
failure:function()
{
alert("failure!");
}
});
}
}).render(document.body,"head");
服务器GetTemplateData.ashx代码也要稍微修改下:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->//主要代码
publicvoidProcessRequest(HttpContextcontext){
stringsql="";
if(context.Request.QueryString["id"]!=null)
{
sql="select*fromxLinkwhereid>"+Convert.ToString(context.Request.QueryString["id"]);
}
else
{
sql="select*fromxLink";
}
StringBuildertempResult=newStringBuilder("{results:[");
stringconnstr=@"DataSource=WIN-7JW7UWR0M27/MSSQL2005;InitialCatalog=xgc;PersistSecurityInfo=True;UserID=sa;[email protected]";
SqlConnectionsqlconn=newSqlConnection(connstr);
SqlCommandcomm=newSqlCommand(sql,sqlconn);
sqlconn.Open();
SqlDataReadersdr=comm.ExecuteReader();
while(sdr.Read())
{
tempResult.Append("{id:'");
tempResult.Append((int)sdr["id"]);
tempResult.Append("',linkname:'");
tempResult.Append((string)sdr["linkname"]);
tempResult.Append("',linkurl:'");
tempResult.Append((string)sdr["linkurl"]);
tempResult.Append("',linkpos:");
tempResult.Append((int)sdr["linkpos"]);
tempResult.Append("},");
}
tempResult.Remove(tempResult.Length-1,1);
tempResult.Append("]}");
context.Response.Write(tempResult);
}
publicvoidProcessRequest(HttpContextcontext){
stringsql="";
if(context.Request.QueryString["id"]!=null)
{
sql="select*fromxLinkwhereid>"+Convert.ToString(context.Request.QueryString["id"]);
}
else
{
sql="select*fromxLink";
}
StringBuildertempResult=newStringBuilder("{results:[");
stringconnstr=@"DataSource=WIN-7JW7UWR0M27/MSSQL2005;InitialCatalog=xgc;PersistSecurityInfo=True;UserID=sa;[email protected]";
SqlConnectionsqlconn=newSqlConnection(connstr);
SqlCommandcomm=newSqlCommand(sql,sqlconn);
sqlconn.Open();
SqlDataReadersdr=comm.ExecuteReader();
while(sdr.Read())
{
tempResult.Append("{id:'");
tempResult.Append((int)sdr["id"]);
tempResult.Append("',linkname:'");
tempResult.Append((string)sdr["linkname"]);
tempResult.Append("',linkurl:'");
tempResult.Append((string)sdr["linkurl"]);
tempResult.Append("',linkpos:");
tempResult.Append((int)sdr["linkpos"]);
tempResult.Append("},");
}
tempResult.Remove(tempResult.Length-1,1);
tempResult.Append("]}");
context.Response.Write(tempResult);
}
效果图:
代码有点乱!