首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

ExtJS Grouping Feature groupHeaderTpl 根據值動態設置顏色

     編輯:程式設計疑難解答

需求

分組表頭模板中,若 sex == 'female' 則將 grad (學歷) 顯示為紅色,否則藍色。

解決方案:XTemplate <tpl if> 條件判斷

features: [{
    ftype: 'grouping',
    groupHeaderTpl: [
        '姓名:{name}',
        '性別:{sex}',
        '學歷:',
        '<tpl if="sex == \'female\'">',
            '<span style="color:red;">{grad}</span>',
        '<tpl else>',
            '<span style="color:blue;">{grad}</span>',
        '</tpl>'
    ].join(''),
    hideGroupedHeader: true,
    enableGroupingMenu: false
}]

關鍵點解析

  • groupHeaderTpl 接收 **字符串數組** 或 **XTemplate 字符串**,最終會 join('')。
  • 模板上下文包含當前組的**第一條記錄數據** (即 values 或 row[0].data),可直接用字段名 {sex}、{grad}。
  • <tpl if="condition"> 支持 JS 表達式,單引號需轉義 \'。
  • 輸出 HTML 片段,可直接用 <span style="color:red;"> 內聯樣式。

進階:複雜邏輯用 <tpl exec> 或 renderer

groupHeaderTpl: new Ext.XTemplate(
    '學歷:',
    '<tpl exec="this.formatGrad(values)">', // 調用自定義函數
    {
        formatGrad: function(values) {
            var color = values.sex === 'female' ? 'red' : 'blue';
            return '<span style="color:' + color + ';">' + values.grad + '</span>';
        }
    }
)

注意事項

  • ExtJS 6+ 推薦用 groupHeaderTpl 字符串數組寫法,舊版用 groupHeaderTpl: '...' 字符串。
  • 分組字段必須在 store.groupField 指定,且數據已按該字段排序。
  • 模板內變量來自**分組第一行數據**,非聚合值。若需聚合 (如計數),用 groupHeaderTpl: '{name} (共 {rows.length} 人)'。

總結

ExtJS groupHeaderTpl 內置強大的 **XTemplate 語法**,直接使用 <tpl if> 條件判斷即可根據字段值動態輸出不同样式/內容,無需重寫渲染器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved