在浏览器和node服务器中使用art-template模板引擎

1、介绍

模板引起最早就是诞生于服务器领域,后来才发展到了前端。

art-template是一款非常流行的模板引擎,它不仅可以在浏览器使用,也可以在 node 中使用

2、安装

可以到github下载,这里使用npm工具下载:npm install art-template

该命令在哪执行就会把包下载到哪里。默认会下载到 node_modules 目录中

3、在 Node 中使用 art-template 模板引擎

首先新建一个文件存储html模板:tpl.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{{ title }}</title>
</head>
<body>
  <p>大家好,我叫:{{ name }}</p>
  <p>我今年 {{ age }} 岁了</p>
  <h1>我来自 {{ province }}</h1>
  <p>我喜欢:{{each hobbies}} {{ $value }} {{/each}}</p>
  <script>
    var foo = '{{ title }}'
  </script>
</body>
</html>
{{}} 语法被称之为 mustache 语法,里面的内容会被模板引擎解析掉
接着新建webserver文件
let http = require('http')
let template = require('art-template')
let fs = require('fs')
let server = http.createServer()
server.on('request', (req, res)=>{
  fs.readFile('./tpl.html', function (err, data) {
    if (err) {
      return console.log('读取文件失败了')
    }
    // 默认读取到的 data 是二进制数据
    // 而模板引擎的 render 方法需要接收的是字符串
    // 所以我们在这里需要把 data 二进制数据转为 字符串 才可以给模板引擎使用
    let ret = template.render(data.toString(), {
      name: 'Jack',
      age: 18,
      province: '广东',
      hobbies: [
        '写代码',
        '唱歌',
        '打游戏'
      ],
      title: '个人信息'
    })
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.end(ret)
  })
})
server.listen(3000, function () {
  console.log('服务运行在3000端口')
})

启动服务,访问http://127.0.0.1:3000/就可以看到结果

 

4、在浏览器端使用art-template模板

在浏览器端需要引用的是template-web.js文件
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>在浏览器中使用art-template</title>
</head>
<body>
  <!-- 
    强调:模板引擎不关心你的字符串内容,只关心自己能认识的模板标记语法,例如 {{}}
   -->
  <script src="node_modules/art-template/lib/template-web.js"></script>
  <script type="text/template" id="tpl">
   
    <section>
      <p>大家好,我叫:{{ name }}</p>
      <p>我今年 {{ age }} 岁了</p>
      <h1>我来自 {{ province }}</h1>
      <p>我喜欢:{{each hobbies}} {{ $value }} {{/each}}</p>
    </section>
  </script>
  <script>
    var ret = template('tpl', {
      name: 'Jack',
      age: 18,
      province: '广东',
      hobbies: [
        '写代码',
        '唱歌',
        '打游戏'
      ]
    })
    var div = document.createElement('div')
    div.innerHTML = ret
    document.body.append(div)
  </script>
</body>
</html>
 
 
 
 
 
原文地址:https://www.cnblogs.com/chuanzi/p/10512516.html