模板引擎 art-template 的基本使用

1. 引入 art-template

<script src="https://unpkg.com/art-template@4.13.2/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 lang="en">

<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/art-template@4.13.2/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文档 (介绍 - art-template)。

Art-template是一款高性能、轻量级的模板引擎,适用于Node.js和浏览器环境。它以简洁明了的语法,支持模板继承、条件判断、循环遍历等常见功能,同时还提供了强大的过滤器和自定义标签功能。 Art-template使用逻辑如下: 1. 安装Art-template 可以通过npm安装Art-template,命令如下: ```npm install art-template --save``` 2. 引入Art-template 在Node.js中,可以使用require语句引入Art-template: ```const template = require('art-template');``` 在浏览器中,可以使用script标签引入Art-template: ```<script src="path/to/art-template.js"></script>``` 3. 编写模板 Art-template使用{{}}包裹变量、表达式或语句。例如,以下是一个简单的模板: ``` <!DOCTYPE html> <html> <head> <title>{{title}}</title> </head> <body> <h1>{{title}}</h1> <p>{{content}}</p> </body> </html> ``` 4. 渲染模板 使用template方法可以将模板渲染成字符串。例如: ``` const template = require('art-template'); const data = { title: 'Art-template', content: 'A lightweight and powerful template engine' }; const html = template('path/to/template', data); console.log(html); ``` 在上面的例子中,我们将data对象传递给了模板,使用{{}}包裹的变量会被替换成data对象中的对应值,最终输出渲染后的HTML字符串。 5. 高级用法 除了基本的变量替换,Art-template还支持模板继承、条件判断、循环遍历等高级用法。例如,以下是一个使用if语句和each语句的模板: ``` {{if isAdmin}} <p>Welcome, admin</p> {{else}} <p>Welcome, user</p> {{/if}} <ul> {{each list}} <li>{{$index}}. {{$value}}</li> {{/each}} </ul> ``` 以上就是Art-template使用逻辑,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值