grid.js表格无法渲染HTML内容,显示纯代码问题求助
解决grid.js表格HTML内容不渲染的问题
问题核心是grid.js默认会转义所有列的HTML内容,防止XSS风险,所以你的HTML字符串会被当成纯文本显示。要让HTML正常渲染,需要在列配置中明确指定允许解析HTML。
解决方案:添加columns配置项
在Grid的配置对象里新增columns数组,对需要渲染HTML的列设置html: true,其他列正常定义即可。
修改后的完整代码:
$("#tableGrid2").Grid({ className: { table: 'table table-sm table-hover table-striped mb-0' }, // 新增columns配置,指定列的渲染规则 columns: [ { name: '自定义内容', html: true }, // 第一列允许渲染HTML { name: 'ID' }, { name: '订单号' }, { name: '总价' } // 对应你后续添加的列 ], pagination: { limit: 20, summary: true, server: { url: (prev, page, limit) => `${prev}?limit=${limit}&offset=${page * limit}` } }, server: { url: `<?= site_url('DashboardController/getVendorSales') ?>`, then: data => data.data.map(product => [ "<div style='padding: 2px; border: 1px solid #ccc;border-radius: 4px;'>" + "<center>hello!</center>" + "</div>", product.id, product.order_number, product.price_total, // Add more properties as needed ]), total: data => data.total // Use total directly here } });
关键说明
columns数组的顺序要和then里返回的数组顺序完全对应- 只有设置了
html: true的列,grid.js才会解析并渲染其中的HTML内容,未设置的列依然保持默认的转义行为 - 如果不需要列名,可以把
name设为空字符串,比如{ name: '', html: true }
内容的提问来源于stack exchange,提问作者Sylwester Zabielski
相关产品推荐
相关产品推荐

