分享

node.js中使用模板引擎art-template

 流楚丶格念 2022-01-14

文章目录

安装:

在这里插入图片描述

npm install art-template

注意:

  • 该命令在哪执行就会把包下载到哪里。默认会下载到 node_modules 目录中
  • node_modules 不要改,也不支持改。

使用

在 Node 中使用 art-template 模板引擎
模板引起最早就是诞生于服务器领域,后来才发展到了前端。

  1. 在需要使用的文件模块中加载 art-template
    只需要使用 require 方法加载就可以了:require('art-template’)
    参数中的 art-template 就是你下载的包的名字
    也就是说你 isntall 的名字是什么,则你 require 中的就是什么
  2. 查文档,使用模板引擎的 API
    http://aui./art-template/zh-cn/docs/

案例

在这里插入图片描述

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>

app.js

var template = require('art-template')
var fs = require('fs')

// 这里不是浏览器
// template('script 标签 id', {对象})

fs.readFile('./tpl.html', function (err, data) {
  if (err) {
    return console.log('读取文件失败了')
  }
  // 默认读取到的 data 是二进制数据
  // 而模板引擎的 render 方法需要接收的是字符串
  // 所以我们在这里需要把 data 二进制数据转为 字符串 才可以给模板引擎使用
  var ret = template.render(data.toString(), {
    name: '李里',
    age: 18,
    province: '北京市',
    hobbies: [
      '写代码',
      '吃饭',
      '打游戏'
    ],
    title: '个人信息'
  })

  console.log(ret)
})

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多