我们在使用layui table展示数据时候,如果对一些字段不加特殊处理,前端表格直接显示数据库存储信息是不合适的,例如数据库有一个类型字段:0和1,0表示国产,1表示进口,前端显然不能直接显示0和1,而是应该根据后端返回的数字进行判断,展示相应的内容。我们在使用layui table展示数据时候,如果对一些字段不加特殊处理,前端表格直接显示数据库存储信息是不合适的,例如数据库有一个类型字段:0和1,0表示国产,1表示进口,前端显然不能直接显示0和1,而是应该根据后端返回的数字进行判断,
layui table
的自定义模板功能能非常方便地解决这个问题,首先看下效果图。
后端返回的完整数据:
{{
"msg": "操作成功!",
"code": "0",
"data": [
{
"id": 1,
"name": "iPhone",
"type": "0",
"price": 6000.0,
"size": 55,
"status": 0,
"description": "说明"
},
{
"id": 2,
"name": "watch",
"type": "1",
"price": 500.0,
"size": 35,
"status": 1,
"description": "说明"
},
{
"id": 3,
"name": "television",
"type": "1",
"price": 1000.0,
"size": 90,
"status": 1,
"description": "说明"
},
{
"id": 4,
"name": "computer",
"type": "1",
"price": 4500.0,
"size": 60,
"status": 1,
"description": "说明"
}
],
"count": 4
}}
方式一:函数转义
所谓函数转义,就是在表格cols的对应列中直接写一段函数:
table.render({
elem: '#goods_table'
, id: 'goodsReload'
, url: '/test/getGoodsInfo'
, method: 'get'
, title: '用户表'
, toolbar: '#goods_headerBar' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
, cols:
[[{type: 'checkbox', fixed: true},
{
field: 'type',
title: '类 型',
width: 100,
align: 'center',
// data就是行数据:{"id": 1,"name": "iPhone","type": "1","price": 6000.0,"size": 55,"status": 0,"description": "说明"}
templet: function (d) {
var type = d.type;
if (type == 0) {
return '<font color="#0000FF">国 产</font>';
} else {
return '<font color="#5FB878">进 口</font>';
}
}
}
// 其他行省略,可去【前端系列-3】获得完整代码
{
fixed: 'right',
title: '操作',
toolbar: '#goos_lineBar',
align: 'center',
width: 120,
style: 'font-size:13px'
}
]]
});
这样的写法,简单直接,缺点是复用性差,有可能导致代码冗余。
方式二:绑定模版选择器
下述是templet对应的模板,它可以存放在页面的任意位置。模板遵循于 laytpl 语法,可读取到返回的所有数据
<script type="text/html" id="typeTpl">
{{# if(d.type ==0 ){ }}
<p style="color: #0000FF">国 产</p>
{{# } else { }}
<p style="color: #00FF00">进 口</p>
{{# } }}
</script>
table.render中的对应列templet内容中直接引用上面的模板即可
table.render({
elem: '#goods_table'
, id: 'goodsReload'
, url: '/test/getGoodsInfo'
, method: 'get'
, title: '用户表'
, toolbar: '#goods_headerBar' //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
, cols:
[[{type: 'checkbox', fixed: true},
{
field: 'type',
title: '类 型',
width: 100,
align: 'center',
templet: '#typeTpl'
}
// 沃梦达
{
fixed: 'right',
title: '操作',
toolbar: '#goos_lineBar',
align: 'center',
width: 120,
style: 'font-size:13px'
}
]]
});
这样的话,如果有多处表格使用同一个模板,代码复用性将得到加强。还有一种方式:直接赋值模版字符
templet: '<div><a href="/detail/{{d.id}}" class="layui-table-link">{{d.title}}</a></div>'
注意:这里一定要被一层 <div></div> 包裹,否则无法读取到模板
织梦狗教程
本文标题为:layui table中使用自定义templet模板


基础教程推荐
猜你喜欢
- 将引号内的内容计算为一个参数 2022-01-01
- 使用 .env 文件进行单元测试 2022-01-01
- IE9 是否支持 CSS3 ::before 和 ::after 伪元素? 2022-01-01
- 从 JSON.parse 捕获异常的正确方法 2022-01-01
- 你如何让 window.open 在 Internet Explorer 7 中工作? 2022-01-01
- 量角器检查元素是否不存在 2022-01-01
- 在 Chart.js 中设置图表高度 2022-01-01
- 我可以使用谷歌驱动器进行 chrome 扩展(不是应用 2022-01-01
- 检测浏览器对跨域 XMLHttpRequests 的支持? 2022-01-01
- javascript中带标签和不带标签有什么区别 2022-01-01