You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KendoUI jQuery Grid列模板结合values字段解析问题求助

问题描述

我定义了如下Kendo UI Grid列,$users是包含text和value字段的关联数组,该列原本可通过values字段正确显示用户全名:

(new Kendo\UI\GridColumn())
                ->field('modified_by')
                ->title($t->translate('card.grid.modified_by'))
                ->values($users)
                ->filterable($filterableMulti)
                ->width(200)
                ->lockable(true)

现在我需要将该列值改为链接,因此添加了template字段来自定义渲染列值:

(new Kendo\UI\GridColumn())
                ->field('modified_by')
                ->title($t->translate('card.grid.modified_by'))
                ->values($users)
                ->filterable($filterableMulti)
                ->width(200)
                ->template('#= (modified_by == null) ? \'\' : \'<a href="' . $this->baseURL . 'profile/\'+modified_by+\'">\'+modified_by+\'</a>\' #')
                ->lockable(true)

问题:我不清楚如何通过values字段中的文本-值数组,将modified_by值解析为用户全名来显示在链接文本中。

解决方案

方法1:传递用户数组到前端,用辅助函数匹配文本

首先在PHP页面中将$users转为JSON并定义全局变量:

<script>
var userList = <?php echo json_encode($users); ?>;
</script>

然后定义前端辅助函数,根据ID获取用户全名:

function getUserName(userId) {
    const user = userList.find(item => item.value == userId);
    return user ? user.text : userId; // 找不到时返回原ID作为 fallback
}

最后修改Grid的模板,调用该函数替换链接文本:

->template('#= (modified_by == null) ? \'\' : \'<a href="' . $this->baseURL . 'profile/\'+modified_by+\'">\'+getUserName(modified_by)+\'</a>\' #')

方法2:后端数据源直接包含用户全名

如果可以修改Grid的数据源,在查询数据时将modified_by对应的用户全名一起查询出来(比如新增modified_by_name字段),模板直接使用该字段即可:

->template('#= (modified_by == null) ? \'\' : \'<a href="' . $this->baseURL . 'profile/\'+modified_by+\'">\'+modified_by_name+\'</a>\' #')

这种方法无需前端额外处理,逻辑更简洁,适合后端可修改数据源的场景。

方法3:利用Kendo Grid内置列配置获取文本

通过Grid实例获取列的values配置,匹配对应的用户文本:

先修改模板调用自定义函数:

->template('#= renderUserLink(data, "modified_by") #')

然后定义前端函数,注意提前将baseURL设为全局变量:

function renderUserLink(dataItem, fieldName) {
    const grid = $("#yourGridId").data("kendoGrid");
    const column = grid.columns.find(col => col.field === fieldName);
    
    if (!column || !dataItem[fieldName]) return '';
    
    const userText = column.values.find(item => item.value == dataItem[fieldName]).text;
    return `<a href="${baseURL}profile/${dataItem[fieldName]}">${userText}</a>`;
}

内容的提问来源于stack exchange,提问作者klaucode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:02:07