zoukankan      html  css  js  c++  java
  • 在 node 中使用模板引擎

    // art-template
    // art-template 不仅可以在浏览器使用,也可以在 node 中使用

    // 安装:
    // npm install art-template
    // 该命令在哪执行就会把包下载到哪里。默认会下载到 node_modules 目录中
    // node_modules 不要改,也不支持改。

    // 在 Node 中使用 art-template 模板引擎
    // 模板引起最早就是诞生于服务器领域,后来才发展到了前端。
    //
    // 1. 安装 npm install art-template
    // 2. 在需要使用的文件模块中加载 art-template
    // 只需要使用 require 方法加载就可以了:require('art-template')
    // 参数中的 art-template 就是你下载的包的名字
    // 也就是说你 isntall 的名字是什么,则你 require 中的就是什么
    // 3. 查文档,使用模板引擎的 API


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

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

    // var tplStr = `
    // <!DOCTYPE html>
    // <html lang="en">
    // <head>
    // <meta charset="UTF-8">
    // <title>Document</title>
    // </head>
    // <body>
    // <p>大家好,我叫:{{ name }}</p>
    // <p>我今年 {{ age }} 岁了</p>
    // <h1>我来自 {{ province }}</h1>
    // <p>我喜欢:{{each hobbies}} {{ $value }} {{/each}}</p>
    // </body>
    // </html>
    // `

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

    console.log(ret)
    })
  • 相关阅读:
    Codeforces Round #368 Div. 2
    TXT文件去除多余空行
    #4247. 串
    #4322. 字符串游戏(strgame)
    #4214. 谢特
    #4155. 咱们去烧菜吧
    #4350. 「十二省联考 2019」字符串问题
    #4349. 「十二省联考 2019」异或粽子
    #4303. 跳蚤
    #4302. 魔法咒语
  • 原文地址:https://www.cnblogs.com/lujieting/p/10296328.html
Copyright © 2011-2022 走看看