If you want to know more about layui, you can click: layui tutorial
## Laytpl is a JavScript template engine that has excellent performance in character parsing, but its shortcomings lie in exception debugging. Since the traditional front-end template engine has become less popular, laytpl may be rewritten in the future. The current direction has not been decided yet, and it is expected to be implemented after layui is relatively stable.Quick use
Different from general character splicing, laytpl’s template can be separated from the data, and the logical processing is centralized in the View layer to improve code maintainability, especially when rendering a large number of templates.layui.use('laytpl', function(){ var laytpl = layui.laytpl;//直接解析字符 laytpl('{{ d.name }}是一位公猿').render({ name: '贤心' }, function(string){ console.log(string); //贤心是一位公猿 }); //你也可以采用下述同步写法,将 render 方法的回调函数剔除,可直接返回渲染好的字符 var string = laytpl('{{ d.name }}是一位公猿').render({ name: '贤心' }); console.log(string); //贤心是一位公猿 //如果模板较大,你也可以采用数据的写法,这样会比较直观一些 laytpl([ '{{ d.name }}是一位公猿', '其它字符 {{ d.content }} 其它字符' ].join('')) });
//第一步:编写模版。你可以使用一个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> //第二步:建立视图。用于呈现渲染结果。 <div id="view"></div> //第三步:渲染模版 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;});
Template syntax
Description | Example | |
Output A normal field without escaping html | ||
Output a normal field without escaping html | ||
JS statement. Generally used for logic processing. Start with a delimiter followed by a # sign. | Note: If you want to output a function, the correct way to write it is: {{ fn() }}, not: {{# fn() }} | |
Filter a specified template area, that is, the template in this area will not be parsed. Note: layui 2.1.6 adds new |
## delimiter If the template's default {{ }} delimiter conflicts with your other templates (usually server-side templates), you can also redefine the delimiter:
laytpl.config({ open: '<%', close: '%>' }); //分割符将必须采用上述定义的 laytpl([ '<%# var type = "公"; %>' //JS 表达式, '<% d.name %>是一位<% type %>猿。' ].join('')).render({ name: '贤心' }, function(string){ console.log(string); //贤心是一位公猿 });
Conclusion Laytpl is used in many modules of layui, such as: layim, table, etc. Although the traditional front-end template engine has become less popular, laytpl can still play a certain role, so give it a try.
The above is the detailed content of How to use layui template engine. For more information, please follow other related articles on the PHP Chinese website!