介绍
- art-template 是一个简约、超快的模板引擎;
- 它采用作用域预声明的技术来优化模板渲染速度,从而获得接近 javaScript 极限的运行性能,并且同时支持 NodeJS 和浏览器;
特性
- 拥有接近 javaScript 渲染极限的性能;
- 调试友好:语法、运行时错误日志精确到模板所在行;支持在模板文件上打断点(webpack loader);
- 支持 Express、Koa、Webpack;
- 支持模板继承与子模板;
- 浏览器版本仅 6kb 大小;
使用
- 使用方式一
<!-- index.html --> <body> <h2>{{ foo }}</h2> <ul> <!-- 遍历 todos--> {{ each todos }} <!-- $value 就是遍历项 --> <li>{{ $value.title }}</li> {{ /each }} </ul> </body>
// app.js const express = require('express') const fs = require('fs') const template = require('art-template') const app = express() const todos = [{ id: 1, title: '吃饭1' }, { id: 2, title: '吃饭2' }, { id: 3, title: '吃饭3' }, { id: 4, title: '吃饭4' } ] app.get('/', (req, res) => { // 1. 读取模板内容 fs.readFile('./views/index.html', 'utf8', (err, templateStr) => { if (err) { return res.status(404).send('404 Not Found.') } // 2. 获取数据 // 3. 渲染这件事儿是在服务端完成的 // 所谓的模板引擎就是在根据特定的规则进行字符串解析替换 const ret = template.render(templateStr, { // 模板中使用的数据 foo: 'bar', todos }) // 把渲染结果发送给客户端 res.end(ret) }) }) app.listen(3000, () => { console.log(`Server running at http://localhost:3000/`) })
- 使用方式二:直接使用 art 模板
<!-- index.art --> <body> <h2>{{ foo }}</h2> <ul> <!-- 遍历 todos--> {{ each todos }} <!-- $value 就是遍历项 --> <li>{{ $value.title }}</li> {{ /each }} </ul> </body>
// app.js const express = require('express') const fs = require('fs') const template = require('art-template') const path = require('path') const app = express() // view engine setup app.engine('html', require('express-art-template')) // 当渲染以 .art 结尾的资源文件的时候使用 express-art-template app.set('view options', { // art-template 模板引擎配置 debug: process.env.NODE_ENV !== 'production' }) app.set('views', path.join(__dirname, 'views')) // 模板文件的存储目录 app.set('view engine', 'html') // 可以省略的模板文件后缀名 const todos = [{ id: 1, title: '吃饭1' }, { id: 2, title: '吃饭2' }, { id: 3, title: '吃饭3' }, { id: 4, title: '吃饭4' } ] app.get('/', (req, res) => { // 只要配置模板引擎,就可以使用 res.render 方法渲染页面了 // 1、读模板文件 2、渲染 3、发送响应 res.render('index', { foo: 'bar', todos }) }) app.listen(3000, () => { console.log(`Server running at http://localhost:3000/`) })
打赏作者
您的打赏是我前进的动力
微信
支付宝
路由器中间件
上一篇
评论