layui的模板引擎可以将数据和模板进行分离,这样我们可以把逻辑放在view层,不用在js中写一大堆模板标签代码,模板引擎的默认分隔符是{{}},正好和我的flask模板分隔符冲突了,以下是我的代码
{% include 'public/header.html' %} <div id="view"></div> <script id="sur_detail" type="text/html"> <table class="layui-table" style="padding: 10px;"> <colgroup> <col width="20%"> <col width="80%"> <col> </colgroup> <tbody> <%# layui.each(d.cms, function(index, item){ %> <tr> <td>文章|点击</td> <td><span class="layui-badge layui-bg-orange"><% item.cid %><span class="layui-bg-blue"><% item.hit %></span></span></td> </tr> <%# }); %> </tbody> </table> </script> <script type="text/html" id="toolbar"> <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="detail">查看</a> </script> <script> layui.use(['form', 'table', 'laytpl', 'layer', 'jquery', 'code'], function(){ var form = layui.form ,table = layui.table ,laytpl = layui.laytpl ,layer = layui.layer ,$ = layui.jquery; laytpl.config({ open: '<%', close: '%>' }); table.render({ elem: '#surlist' ,url: '{{ url_for("fp.ajaxSu") }}' ,page: true //开启分页 ,done: function(res, curr, count){ console.log(res); } ,cols: [[ //表头 // {checkbox: true, fixed: true} {field: 'id', title: 'Id', width:'8%', 'fixed':'left'} ,{field: 'name', title: '名字', width:'26%'} ,{field: 'enabled', title: '是否启用', width:'10%'} ,{field: 'createdTime', title: '创建时间', width: '16%'} ,{field: 'updateTime', title: '最后更新时间', width: '16%'} ,{title: '操作',fixed: 'right', width:'8%', align:'center', toolbar: '#toolbar'} ]] ,limit: "{{ page_limit }}" }); table.on('tool(surlist)', function(obj){ var data = obj.data; if(obj.event === 'detail'){ var getTpl = sur_detail.innerHTML ,view = document.getElementById('view'); laytpl(getTpl).render(data, function(html){ view.innerHTML = html; }); } }); }); </script> {% include 'public/footer.html' %}
监听工具条事件,然后将json数据渲染到视图view绑定的dom上,使用比较简单,直接看实例应该能够理解