ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] 官网: http://www.layui.com/doc/modules/laytpl.html#syntax ## 基本代码 ``` <ul id="userList"></ul> <script id="userListTpl" type="text/html"> {{# layui.each(d, function(index, item){ }} <li>{{ item.user_name }}</li> {{# }); }} </script> <script> // tpl and view var getTpl = userListTpl.innerHTML , view = document.getElementById('userList'); //url and data var url = "/agent/main/apiUserList/companyId/"; var data = { "companyId":data.field.mobile }; //ajax-get $.get(url,data,function(data){ //列表 $("#userList").html(""); laytpl(getTpl).render(data, function(html){ view.innerHTML = html; }); }); </script> ``` ## 为空判断 ``` {{ item.memo || '暂无' }} ``` ## 其他 ``` <div>{{ d.content }}</div> <h2>{{= d.title }}</h2> <div> {{! 这里面的模板不会被解析 !}}</div> {{# var fn = function(){ return '2017-08-18'; }; if(true){ }} 开始日期:{{ fn() }} {{# } else { }} 已截止 {{# } }} ``` ## if ``` {{# if(d.list.length === 0){ }} 无数据 {{# } }} ``` ## if else ``` {{# if(d.list.length === 0){ }} 1 {{# } else { }} 2 {{# } }} ``` ## laytpl中如何调用自定义函数 ``` <script> laytpl.fn = function(){ return '自定义函数' } </script> 模板中调用: {{# laytpl.fn(); }} ``` ## 实例 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../layui/css/layui.css"/> </head> <body> <div id="view"></div> <script id="demo" type="text/html"> <h3>自定义函数:{{ layui.laytpl.fn() }}</h3> <h3>自定义函数2:{{ layui.laytpl.fn1('hello') }}</h3> <h3>自定义函数2:{{ layui.laytpl.returnFloat('3.100') }}</h3> <h3>{{ d.title }}</h3> </script> <script src="../layui/layui.js"></script> <script> layui.use('laytpl',function(){ var laytpl = layui.laytpl; laytpl.fn = function(){ return 'test'; } laytpl.fn1=function (username) { return username; } laytpl.returnFloat = function(value){ var value=Math.round(parseFloat(value)*100)/100; var xsd=value.toString().split("."); if(xsd.length==1){ value=value.toString()+".00"; return value; } if(xsd.length>1){ if(xsd[1].length<2){ value=value.toString()+"0"; } return value; } } var data = { //数据 "title":"Layui常用模块" ,"list":[{"modname":"弹层","alias":"layer","site":"layer.layui.com"},{"modname":"表单","alias":"form"}] } var getTpl = demo.innerHTML ,view = document.getElementById('view'); laytpl(getTpl).render(data, function(html){ view.innerHTML = html; }); }); </script> </body> </html> ```