layui下载地址:
最终效果:
模板引擎文档 手册地址:
https://www.layui.com/doc/modules/laytpl.html
与一般的字符拼接不同的是,laytpl 的模板可与数据分离,集中把逻辑处理放在 View 层,提升代码可维护性,尤其是针对大量模板渲染的情况。
也可以将模板存储在页或其它任意位置:
以下是代码思路:
- 将代码存到script标签里.
- 在script渲染数据.
- 插入指定的view标签里.
form.render();
注意:a.form表单需要放在class="layui-form"类里,b.动态渲染的表单,需要用更新渲染
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>非模块化方式使用layui</title>
<link rel="stylesheet" href="./layui/css/layui.css">
</head>
<body>
<!-- 你的HTML代码 -->
<!-- 第二步:建立视图。用于呈现渲染结果。 -->
<div id="view"></div>
<div id="view2"></div>
</body>
<!-- //第一步:编写模版。你可以使用一个script标签存放模板,如: -->
<script id="demo" type="text/html">
<h3>{{ d.title }}</h3>
<ul>
{{# layui.each(d.list, function(index, item){ }}
<li>
<span>{{ item.modname }}</span>
<span>{{ item.alias }}:</span>
<span>{{ item.site || '' }}</span>
</li>
{{# }); }}
{{# if(d.list.length === 0){ }}
无数据
{{# } }}
</ul>
</script>
<script id="demo2" type="text/html">
<form class="layui-form"> <!-- 提示:如果你不想用form,你可以换成div等任何一个普通元素 -->
<div class="layui-form-item">
<label class="layui-form-label">复选框</label>
<div class="layui-input-block">
<!-- <input type="checkbox" name="like[write]" title="写作">
<input type="checkbox" name="like[read]" title="阅读"> -->
{{# layui.each(d.answers_list, function(index, item){ }}
<input type="checkbox" value="{{ item.id }}" name="answers[{{ item.answers }}]" title="{{ item.answers }}">
<!-- <div class="layui-unselect layui-form-checkbox" lay-skin="primary"><span>{{ item.answers }}</span><i class="layui-icon layui-icon-ok"></i></div> -->
{{# }) }}
<hr>
{{# layui.each(d.answers_list, function(index, item){ }}
<input type="checkbox" value="{{ item.id }}" name="{{ item.answers }}" title="{{ item.answers }}" data-option_id="{{ item.id }}" lay-skin="primary">
<!-- <div class="layui-unselect layui-form-checkbox" lay-skin="primary"><span>{{ item.answers }}111</span><i class="layui-icon layui-icon-ok"></i></div> -->
{{# }) }}
</div>
</div>
</form>
</script>
<script src="./layui/layui.all.js"></script>
<script>
//由于模块都一次性加载,因此不用执行 layui.use() 来加载对应模块,直接使用即可:
;!function(){
var layer = layui.layer
,form = layui.form,
laytpl = layui.laytpl;
layer.msg('Hello World');
//第三步:渲染模版
var data = { //数据
"title":"Layui常用模块"
,"list":[
{"modname":"弹层","alias":"layer","site":"layer.layui.com"},
{"modname":"表单","alias":"form"}
]
,"answers_list":[
{"id":"1","answers":"A"},
{"id":"2","answers":"B"},
{"id":"3","answers":"D"},
{"id":"4","answers":"E"}
]
}
//dome1
var getTpl = demo.innerHTML
,view = document.getElementById('view');
laytpl(getTpl).render(data, function(html){
view.innerHTML = html;
});
//dome2
var demo2html = demo2.innerHTML
,view2 = document.getElementById('view2');
laytpl(demo2html).render(data, function(html){
view2.innerHTML = html;
});
form.render(); //更新全部
}();
</script>
</html>