1.定义容器(用于填充渲染后的script)
<div id="view" style="display: none;"></div>
2.定义script模板
<script type="text/html" id="myModal"> <div style="padding: 20px;"> <form id="userForm" class="layui-form" lay-filter="editWin"> <input type="hidden" id="uid" name="uid" value={{=d.id}}> <div class="layui-form-item"> <label class="layui-form-label">角色类别:</label> <div class="layui-input-block"> <select id="roleTypeSelect" class="layui-select"> <option value="-1">请选择角色类别</option> {{# layui.each(d.roleTypeList, function(index, item){ }} {{# if(d.roleType == item.dicVal ){ }} <option value="{{ item.dicVal}}" selected="selected">{{ item.dicName}}</option> {{# }else{ }} <option value="{{ item.dicVal}}" >{{ item.dicName}}</option> {{# } }} {{# }); }} </select> </div> </div> </form> </div> </script>
3.laytpl动态绑定渲染script
// 此处模拟展示data数据
{
"roleTypeList" : [
{"dicVal" : "01" , "dicName" : "管理员"},
{"dicVal" : "02" , "dicName" : "游客"},
{"dicVal" : "03" , "dicName" : "普通用户"},
],
"id" : 7,
"roleType" : "03"
}
var scriptHtml = document.getElementById("myModal").innerHTML; var view = document.getElementById("view"); // 通过data数据渲染script模板 laytpl(scriptHtml).render(data, function (html) { view.innerHTML = html; }); // layui弹框,类似model模态框 layer.open({ type: 1, title: '弹框名称', offset: '20px', area: ['500px', '330px'], closeBtn: false, content: $("#view") }) form.render('select'); // layui中动态设置html的某个类型标签时,需要layui.render('type')刷新
参考地址
laytpl标签: {{# }} 参数格式: { "field" : "值", "keyList" : [ {"field":"值1"}, {"field":"值2"} ] } // 模板中使用d表示传入参数 1.输出字段,不转义html {{ d.field }} 2.输出字段,转义html {{= d.field }} 3.js表达式 {{# if(d.field=="XXX"){ }} // 输出值 {{# } }} 4.遍历集合 {{# layui.each(d.keyList, function(index, item){ }} {{# item.field }} {{# }); }}