art-Template简单用法

2,788 阅读2分钟

模板引擎

2019.07.12

art-Template

art-template 支持标准语法与原始语法。标准语法可以让模板易读写,而原始语法拥有强大的逻辑表达能力。 标准语法支持基本模板语法以及基本 JavaScript 表达式;原始语法支持任意 JavaScript 语句,这和 EJS 一样。

简单使用(原生语法)

  1. 准备数据

    • 可以是模拟的数据,也可以是请求的后台数据
    var data = [
      {
        "url": "http://www.study.com/itcast30/day02/jdM/images/detail01.jpg",
        "nowPrice": "<b>10.00</b>",
        "oldPrice": "100.00"
      },
      {
        "url": "http://www.study.com/itcast30/day02/jdM/images/detail01.jpg",
        "nowPrice": "10.00",
        "oldPrice": "1001.00"
      },
      {
        "url": "http://www.study.com/itcast30/day02/jdM/images/detail01.jpg",
        "nowPrice": "10.00",
        "oldPrice": "100.00"
      },
    ]
    
  2. 准备模版

    模版语法必须写在 <% %> 原生的模版语法和js语法一样 输出语法 <%= %> 字符串 输出语法 <%=# %> html 当需要渲染的数据中有标签时使用 输出语法 <%- value %> 原文输出 js语法 变量 函数 分支循环 可以在原生语法中使用

    <script type="text/template" id="template">
      <!-- <% var $ = get().$; %>  -->
      //用于接收传递的全局变量
      <% $imports.log('Hello') %> 
      <% $.each(list,function(i,item){ %>
        <tr>
            <td><%=i+1 %></td>
            <td><img width="100" src="<%=item.url %>" alt=""></td>
            <td><%=#item.nowPrice %></td>
            <% if(item.oldPrice > 1000){ %>
                <td style="color: red"><%=item.oldPrice %></td>
            <% }else{ %>
                <td><%=item.oldPrice %></td>
            <% } %>
        </tr>
      <% }); %>
    </script>
    
    

    不能使用外部变量(全局变量也不能),只能使用传入的数据

     //方法1:数据和模版绑定时直接将全局函数传进去 web无法使用
     template('template',{list:data,$:jQuery,console:console});
     //方法2:使用辅助函数 帮助申明一个模版内能使用的函数 web无法使用
     template.helper('get',function () {
       return {$:jQuery,console:console};
     });
     //方法3:通过template.defaults.imports导入的函数或变量 web版本方法
     template.defaults.imports.log = console.log;
     <% $imports.log('Hello') %>
    
  3. 数据和模版绑定--->生成html格式的代码

    var html = template('template',{list:data});
    

    参数1:模版的ID 参数2:数据(强制要求:必须是对象) 模版内使用的就是对象的数据 当作了变量

  4. 显示页面

    document.querySelector('tbody').innerHTML = html;
    
  5. 帮助申明一个模版内能使用的函数 web版本无法用

    template.helper('get',function () {
      return {$:jQuery,console:console};
    });
    

    参数1:模版的ID 参数2:数据(强制要求:必须是对象) 模版内使用的就是对象的数据 当作了变量

  6. 内置变量清单 $data 传入模板的数据; $imports 外部导入的变量以及全局变量; print 字符串输出函数; include 子模板载入函数 extend 模板继承模板导入函数 block 模板块生命函数

参考1 参考2 参考3