天天看点

模板引擎 art-template 的基本使用1. 引入 art-template2. 准备好模板3. 获取模板4. 将模板内容插入到DOM元素中5. 完整示例注:art-template文档 (介绍 - art-template)。

1. 引入 art-template

<script src="https://unpkg.com/[email protected]/lib/template-web.js"></script>
           

2. 准备好模板

<script id="tpl-students" type="text/html">
  {{each students}}
    <li>{{$value.name}}--{{$value.age}}--{{$value.sex}}</li>
  {{/each}}
</script>
           

3. 获取模板

const tplData = template('tpl-students',{
  // students:students
  students
});
           

4. 将模板内容插入到DOM元素中

const list = document.getElementById('list');
list.innerHTML = tplData;
           

5. 完整示例

<!DOCTYPE html>
<html >

<head>
  <meta charset="UTF-8" />
  <title>模板引擎 art-template 的基本使用</title>
</head>

<body>
  <p>学生信息表</p>
  <ul id="list"></ul>

  <!-- 1.引入 art-template -->
  <script src="https://unpkg.com/[email protected]/lib/template-web.js"></script>

  <!-- 2.准备好模板 -->
  <script id="tpl-students" type="text/html">
    {{each students}}
      <li>{{$value.name}}--{{$value.age}}--{{$value.sex}}</li>
    {{/each}}
  </script>

  <script>
    // 学生数据
    const students = [
        {
          name: 'Alex',
          age: 18,
          sex: 'male'
        },
        {
          name: '张三',
          age: 28,
          sex: 'male'
        },
        {
          name: '李四',
          age: 20,
          sex: 'female'
        }
      ];

      // 3.获取模板
      const tplData = template('tpl-students',{
        // students:students
        students
      });

      // 4.将模板引擎输出的字符串,传递给DOM元素的innerHTML属性
      const list = document.getElementById('list');
      list.innerHTML = tplData;

      console.log(tplData);
  </script>
</body>

</html>
           
模板引擎 art-template 的基本使用1. 引入 art-template2. 准备好模板3. 获取模板4. 将模板内容插入到DOM元素中5. 完整示例注:art-template文档 (介绍 - art-template)。

注:art-template文档 (介绍 - art-template)。