Ext JS 學習(11) Ext.Template的使用

XTemplate是Extjs裏面的模板組件.
下面我們看個最簡單的例子.
效果圖:

js代碼:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


-->Ext.onReady(function(){
    
//數據源
    var data={
       name:
"博客園",
       read:[{
           book:
'<<道不遠人>>',
           date:
'2007-7-7'
       },{
           book:
"<<大話設計模式>>",
           date:
"2006-6-6"
       }]
    }
    
//呈現組件
    var mypanel=new Ext.Panel({
      width:
400,
      id:
"mypanel",
      title:
"XtemplateData簡單示例",
      renderTo:Ext.getBody()
    });
    
//創建模板
    var tpl=new Ext.XTemplate(
        
'<table><tr><th>名稱:{name}</th></tr>',
        
'<tr><td>',
        
'<tpl for="read">',
             
'<p>編號:{#},書:{book},日期:{date}</p>',
        
'</tpl></td></tr></table>'
    );
    
//重寫綁定模板
    tpl.overwrite(mypanel.body,data);
})

簡要說明:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


-->/*
var tpl=new Ext.XTemplate(
        '<table><tr><th>名稱:{name}</th></tr>',
        '<tr><td>',
        '<tpl for="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.,<tpl for="read">//對於多維對象(如擁有多條數據的表),使用tpl和for配合使用,會使用tpl的格式把數據一條一條輸出,read爲上級節點
5.{.}//對於一維對數據的對象,如color: ['Red', 'Blue', 'Black'],可以用{.}按照tpl模板逐一輸出,如: 
   '<tpl for="color">',
       
'<div> {.}</div>',
    
'</tpl>'
6.{#}//表示循環的索引
7.parent.***//在子對象中訪問父對象元素,使用parent,如:{parent.name}
8.if//'<tpl if="age &gt; 1">', 
            '<p>{name}</p>',
        
'</tpl>',
    
//if實現有條件的邏輯判斷,很容易使用
9.其他幾個常用的參數:
     xindex
//循環模板的當前索引index(從1開始),用[]。 
     xcount//循環模板循環的次數。 用[]
  舉例:
   
'<tpl for="read">',
             
'<p>編號:{#},書:{book},日期:{date},奇偶:{[xindex%2==0?"偶數":"奇數"]},次數:{[xcount]}</p>',
        
'</tpl>
10.模板成員函數(借用api下):
var tpl = new Ext.XTemplate(
    
'<tpl for="kids">',
        
'<tpl if="this.isGirl(name)">',
            
'<p>Girl: {name} - {age}</p>',
        '</tpl>',
        
'<tpl if="this.isGirl(name) == false">',
            
'<p>Boy: {name} - {age}</p>',
        
'</tpl>',
    
'</tpl></p>', {
     isGirl: 
function(name){
         
return name == 'Sara Grace';
     },
     isBaby: 
function(age){
        
return age < 1;
     }
});

接下來,我們做個服務器的例子(好像很多朋友對這個要求很強烈啊)
實例演示:用模板呈現服務器數據
效果圖:

html代碼:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


--><div id="container">
  
</div>

css代碼:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


--> <style type="text/css">
        body
        
{
            font-size
:12px
            
}
       #container
       
{
           border
:1px solid black;
           width
:330px;
           
}
       td,th
       
{
           border-bottom
:1px dashed black;
           
}
           th
           
{
               text-align
:center;
               
}
       .namewidth
       
{
               width
:120px; 
           
}
           .urlwidth
           
{
               width
:150px;
               
}
    
</style>

js代碼:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


-->Ext.onReady(function(){

    

var mydata;
    Ext.Ajax.request({
      url:
"getXtemplateData.ashx",//服務器端地址
      success:function(request){
             mydata
=request.responseText;//服務器端文本數據
             mydata=eval('('+mydata+')');//使用eval把文本數據轉換爲json對象
             //或者用extjs自帶的方法:mydata=Ext.util.JSON.decode(mydata),效果相同
             
var tpl2=new Ext.XTemplate(
             
'< table><thead><tr><th>編號</th><th class= "namewidth">名稱</th><th class="urlwidth">地址</th>< th>位置</th></tr></thead><tbody>',
            
'<tpl for="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的代碼:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


--><%@ WebHandler Language="C#" Class="getXtemplateData" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public class getXtemplateData : IHttpHandler {
    
    
public void ProcessRequest (HttpContext context) {
        
        StringBuilder tempResult 
= new StringBuilder("{results:[");

        

string connstr = @"Data Source=WIN-7JW7UWR0M27/MSSQL2005;Initial Catalog=xgc;Persist Security Info=True;User ID=sa;Password=************";
        SqlConnection sqlconn 
= new SqlConnection(connstr);
        SqlCommand comm 
= new SqlCommand("select * from xLink", sqlconn);
        sqlconn.Open();
        SqlDataReader sdr 
= 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 
- 11);//去掉多餘的那個逗號
        tempResult.Append("]}");
        context.Response.Write(tempResult);
//輸出
    }
 
    
public bool IsReusable {
        
get {
            
return false;
        }
    }

}

今天對XTemplate做了個簡單介紹,下篇我們開始TreePanel的學習討論~!
最後推薦個網站:浪曦視頻網 ,謝謝支持!
============補充==========
我們在上面對基礎上作個查詢:
html代碼爲:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


--><div id="head"><input id="linkid" type="text" /></div>
  
<div id="container">
  
</div>

js代碼在上面js的基礎上添加下面部分:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


-->    new Ext.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");

服務器GetTemplateData.ashx代碼也要稍微修改下:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)


-->//主要代碼
 public void ProcessRequest (HttpContext context) {
        string sql
="";
        
if (context.Request.QueryString["id"!= null)
        {
            sql 
= "select * from xLink where id>"+Convert.ToString(context.Request.QueryString["id"]);
        }
        
else
        {
             sql
="select * from xLink";
        }
        StringBuilder tempResult 
= new StringBuilder("{results:[");

        string connstr 

= @"Data Source=WIN-7JW7UWR0M27/MSSQL2005;Initial Catalog=xgc;Persist Security Info=True;User ID=sa;[email protected]";
        SqlConnection sqlconn 
= new SqlConnection(connstr);
        SqlCommand comm 
= new SqlCommand(sql, sqlconn);
        sqlconn.Open();
        SqlDataReader sdr 
= 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 
- 11);
        tempResult.Append(
"]}");
        context.Response.Write(tempResult);
    }

效果圖:
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章