smarty/index.js

89 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-05-25 15:35:26 +08:00
/**
* nodeJS 模板引擎(依赖doJS框架)
* @authors yutent (yutent@doui.cc)
* @date 2015-12-28 13:57:12
*
*/
'use strict'
require('es.shim')
const Tool = require('./lib/tool')
2020-04-06 23:33:47 +08:00
function hash(str) {
return Buffer.from(str).toString('hex')
}
2018-05-25 15:35:26 +08:00
class Smarty {
constructor(opt) {
2020-04-06 23:33:47 +08:00
this.opt = { cache: true, ext: '.tpl' }
2018-05-25 15:35:26 +08:00
if (opt) {
Object.assign(this.opt, opt)
}
2020-04-06 23:33:47 +08:00
this.__REG__ = new RegExp(this.opt.ext + '$')
2018-05-25 15:35:26 +08:00
this.tool = new Tool(this.opt)
2020-04-06 23:33:47 +08:00
this.__DATA__ = Object.create(null) // 预定义的变量储存
this.__CACHE__ = Object.create(null) // 模块缓存
2018-05-25 15:35:26 +08:00
}
config(key, val) {
this.tool.config(key, val)
}
/**
* 定义变量
* @param {Str} key 变量名
* @param {any} val
*/
assign(key, val) {
key += ''
if (!key) {
return this
}
2020-04-06 23:33:47 +08:00
this.__DATA__[key] = val
2018-05-25 15:35:26 +08:00
return this
}
/**
* [render 模板渲染]
* @param {String} tpl 模板路径
* @param {String} uuid 唯一标识
2020-04-06 23:33:47 +08:00
* @param {Boolean} noParse 不解析直接读取
2018-05-25 15:35:26 +08:00
* @return {Promise} 返回一个Promise对象
*/
2020-04-06 23:33:47 +08:00
render(tpl = '', uuid = '', noParse = false) {
var key = null
2018-05-25 15:35:26 +08:00
if (!this.tool.opt.path) {
throw new Error('Smarty engine must define path option')
}
if (!tpl) {
return Promise.reject('argument[tpl] can not be empty')
}
2020-04-06 23:33:47 +08:00
if (!this.__REG__.test(tpl)) {
tpl += this.opt.ext
2018-05-25 15:35:26 +08:00
}
2020-04-06 23:33:47 +08:00
key = hash(tpl + uuid)
2018-05-25 15:35:26 +08:00
2020-04-06 23:33:47 +08:00
if (this.opt.cache && this.__CACHE__[key]) {
return Promise.resolve(this.__CACHE__[key])
2018-05-25 15:35:26 +08:00
}
2020-04-06 23:33:47 +08:00
this.__CACHE__[key] = this.tool.__tpl__(tpl, noParse)
if (noParse) {
return this.__CACHE__[key]
}
2018-05-25 15:35:26 +08:00
try {
2020-04-06 23:33:47 +08:00
this.__CACHE__[key] = this.tool.parse(this.__CACHE__[key], this.__DATA__)
return Promise.resolve(this.__CACHE__[key])
2018-05-25 15:35:26 +08:00
} catch (err) {
return Promise.reject(err)
}
}
}
module.exports = Smarty