mm_tpl 2.4.5 → 2.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,29 @@
1
1
  # mm_tpl
2
2
 
3
- 这是超级美眉模板帮助类模块,用于MVC模式下的视图渲染。基于art-template模板引擎,提供了更强大的模板渲染功能。
3
+ 超级美眉模板引擎模块,基于art-template模板引擎,提供强大的MVC模式视图渲染功能,支持钩子系统、主题切换和缓存机制。
4
+
5
+ [English Documentation](README_EN.md) | [中文文档](README.md)
6
+
7
+ ## 目录
8
+
9
+ - [特性](#特性)
10
+ - [安装](#安装)
11
+ - [快速开始](#快速开始)
12
+ - [高级特性](#高级特性)
13
+ - [API 参考](#api-参考)
14
+ - [注意事项](#注意事项)
15
+ - [开发](#开发)
16
+ - [许可证](#许可证)
17
+
18
+ ## 特性
19
+
20
+ - 🚀 基于art-template高性能模板引擎
21
+ - 🔧 支持多种模板语法规则
22
+ - 🎨 主题切换和模板文件优先级搜索
23
+ - ⚡ 内置缓存机制提升性能
24
+ - 🔌 强大的钩子系统支持
25
+ - 📁 灵活的目录结构支持
26
+ - 🛡️ 完善的错误处理机制
4
27
 
5
28
  ## 安装
6
29
 
@@ -8,35 +31,47 @@
8
31
  npm install mm_tpl
9
32
  ```
10
33
 
11
- ## 基本使用
34
+ ## 快速开始
12
35
 
13
- ### 1. 初始化模板引擎
36
+ ### 1. 安装依赖
37
+
38
+ ```bash
39
+ npm install mm_tpl
40
+ ```
41
+
42
+ ### 2. 初始化模板引擎
14
43
 
15
44
  ```javascript
16
45
  const {Tpl} = require('mm_tpl');
46
+
47
+ // 创建模板实例
17
48
  const tpl = new Tpl({
18
- // 可选配置参数
19
49
  root: process.cwd(), // 根目录
20
50
  default_dir: "./template/", // 默认模板目录
21
51
  default_theme: 'default', // 默认主题
22
52
  extname: ".html", // 模板文件扩展名
23
53
  cache_root: './cache', // 缓存目录
24
- cache_extname: '.cache.html' // 缓存文件扩展名
54
+ cache_extname: '.cache.html', // 缓存文件扩展名
55
+ rules: [nativeRule, artRule, htmlRule, jsRule, pyRule, pyRule2] // 模板规则
25
56
  });
26
57
  ```
27
58
 
28
- ### 2. 基础模板渲染
59
+ ### 3. 基础模板渲染
29
60
 
30
61
  ```javascript
31
62
  // 简单变量替换
32
63
  const result = tpl.render("<div>${message}</div>", {
33
64
  message: "Hello World"
34
65
  });
35
-
36
66
  // 输出: <div>Hello World</div>
67
+
68
+ // 编译模板函数
69
+ const compiled = tpl.compile("<div>${name} - ${age}</div>");
70
+ const result2 = compiled({ name: "张三", age: 25 });
71
+ // 输出: <div>张三 - 25</div>
37
72
  ```
38
73
 
39
- ### 3. 循环渲染
74
+ ### 4. 循环渲染
40
75
 
41
76
  ```javascript
42
77
  // 数组循环
@@ -90,23 +125,32 @@ const eachResult = tpl.render(`
90
125
  // </ul>
91
126
  ```
92
127
 
93
- ### 4. 视图渲染
128
+ ### 5. 视图渲染
94
129
 
95
130
  ```javascript
96
131
  // 设置全局变量
97
132
  $.globalBag.siteName = "我的网站";
98
133
 
99
134
  // 设置视图变量
100
- tpl.viewBag.title = "首页";
135
+ tpl.set({
136
+ title: "首页",
137
+ keywords: "关键词"
138
+ });
101
139
 
102
140
  // 渲染视图文件
103
141
  const html = tpl.view("./views/index.html", {
104
142
  user: { name: "张三" }
105
143
  });
106
144
  // 输出: 渲染结果 <div>Hello World</div>
145
+
146
+ // 获取视图变量
147
+ const title = tpl.get("title");
148
+
149
+ // 删除视图变量
150
+ tpl.del("keywords");
107
151
  ```
108
152
 
109
- ### 5. 缓存机制
153
+ ### 6. 缓存机制
110
154
 
111
155
  ```javascript
112
156
  // 使用缓存渲染视图
@@ -117,11 +161,13 @@ const html = tpl.view("./views/page", {
117
161
  cache_filename: "./cache" // 缓存文件名
118
162
  });
119
163
 
120
- // 清除指定目录的缓存
121
- tpl.clear_cache('./views/mall');
164
+ // 清除缓存
165
+ tpl.clearCache('./views/mall'); // 清除指定目录缓存
166
+ // 或
167
+ tpl.clearCache(); // 清除所有缓存
122
168
  ```
123
169
 
124
- ### 6. 钩子系统
170
+ ### 7. 钩子系统
125
171
 
126
172
  #### 添加函数钩子
127
173
  ```javascript
@@ -132,7 +178,7 @@ $.hook.addFunc('list', async function(viewBag, req, type) {
132
178
  viewBag.user_id = query.user_id;
133
179
  }
134
180
  return someData;
135
- });
181
+ }, 100, 'listFunc'); // sort: 优先级, alias: 别名
136
182
  ```
137
183
 
138
184
  #### 添加动作钩子
@@ -149,26 +195,45 @@ $.hook.addFilter('content', function(viewBag, content, param) {
149
195
  }, 1, "contentFilter");
150
196
  ```
151
197
 
152
- #### 在模板中使用钩子
198
+ #### 执行钩子
153
199
  ```javascript
154
- // 运行函数钩子
155
- await tpl.runFunc('list', {
156
- query: { page: 1 }
157
- }, 'article');
200
+ // 执行函数钩子
201
+ const result = await tpl.runFunc('list', { query: { page: 1 } }, 'article');
202
+
203
+ // 执行动作钩子
204
+ const actionResult = tpl.runHook('header', { param: 'value' });
205
+
206
+ // 在模板中使用钩子
207
+ const html = tpl.render(`
208
+ <div>
209
+ ${hookAction('header')}
210
+ ${hookFilter('content', '原始内容')}
211
+ </div>
212
+ `, data);
213
+ ```
158
214
 
159
- // 在模板中使用动作钩子
160
- ${hook_action('header')}
215
+ #### 删除钩子
216
+ ```javascript
217
+ // 删除指定钩子
218
+ $.hook.delFunc('list', 'listFunc');
219
+ $.hook.delAction('header', 'headerAction');
220
+ $.hook.delFilter('content', 'contentFilter');
161
221
 
162
- // 在模板中使用过滤器钩子
163
- ${hook_filter('content', '原始内容')}
222
+ // 清空所有钩子
223
+ $.hook.clear();
164
224
  ```
165
225
 
166
226
  ## 高级特性
167
227
 
168
- ### 1. 主题支持
228
+ ### 1. 主题和目录支持
169
229
  ```javascript
170
230
  // 设置当前主题
171
231
  tpl.current_theme = "dark";
232
+
233
+ // 模板文件查找顺序(优先级从高到低):
234
+ // 1. diy目录(自定义目录)
235
+ // 2. 当前主题目录
236
+ // 3. 默认主题目录
172
237
  ```
173
238
 
174
239
  ### 2. 模板规则
@@ -183,36 +248,80 @@ tpl.current_theme = "dark";
183
248
  ```javascript
184
249
  const html = tpl.view("./template.html", data);
185
250
  if (tpl.error) {
186
- $.log.error("渲染错误:", tpl.error);
251
+ console.error("渲染错误:", tpl.error);
187
252
  }
188
253
  ```
189
254
 
190
- ### 4. 视图背包操作
255
+ ### 4. 字符转义
191
256
  ```javascript
192
- // 设置视图变量
193
- tpl.set({
194
- title: "页面标题",
195
- keywords: "关键词"
196
- });
257
+ // 自动转义特殊字符
258
+ const escaped = tpl.escape("<div>${content}</div>");
259
+ // 输出: <div>·$·{content}</div>
197
260
 
198
- // 获取视图变量
199
- const title = tpl.get("title");
261
+ // 还原转义字符
262
+ const restored = tpl.escape(escaped, true);
263
+ // 输出: <div>${content}</div>
264
+ ```
200
265
 
201
- // 删除视图变量
202
- tpl.del("title");
203
- // 或批量删除
204
- tpl.del(["title", "keywords"]);
266
+ ### 5. 全局挂载
267
+ ```javascript
268
+ // 自动挂载到全局对象
269
+ if (global.$ && !$.Tpl) {
270
+ $.Tpl = Tpl;
271
+ $.tpl = new Tpl();
272
+ }
205
273
  ```
206
274
 
275
+ ## API 参考
276
+
277
+ ### Tpl 类方法
278
+
279
+ - `constructor(config)` - 构造函数,创建模板实例
280
+ - `setConfig(config)` - 设置配置参数
281
+ - `render(body, model, options)` - 渲染模板字符串
282
+ - `compile(body, options)` - 编译模板为函数
283
+ - `view(file, model, options)` - 渲染模板文件
284
+ - `set(obj)` - 设置视图数据
285
+ - `get(key)` - 获取视图数据
286
+ - `del(keys)` - 删除视图数据
287
+ - `clearCache(path, file)` - 清除缓存
288
+ - `runFunc(name, req, ...args)` - 执行函数钩子
289
+ - `runHook(name, req, ...args)` - 执行动作钩子(runFunc别名)
290
+ - `escape(body, restore)` - 转义/还原字符
291
+
292
+ ### Hook 类方法
293
+
294
+ - `addFunc(name, func, sort, alias)` - 添加函数钩子
295
+ - `addAction(name, func, sort, alias)` - 添加动作钩子
296
+ - `addFilter(name, func, sort, alias)` - 添加过滤器钩子
297
+ - `runFunc(name, model, req, ...args)` - 执行函数钩子
298
+ - `runAction(name, model, ...args)` - 执行动作钩子
299
+ - `runFilter(name, model, ret, ...args)` - 执行过滤器钩子
300
+ - `delFunc(name, alias)` - 删除函数钩子
301
+ - `delAction(name, alias)` - 删除动作钩子
302
+ - `delFilter(name, alias)` - 删除过滤器钩子
303
+ - `clear(name)` - 清空钩子
304
+
207
305
  ## 注意事项
208
306
 
209
- 1. 确保模板目录具有正确的读写权限
210
- 2. 使用缓存时注意及时清理过期缓存
211
- 3. 钩子的优先级数值越小,执行顺序越靠前
212
- 4. 建议在生产环境开启模板缓存以提高性能
213
- 5. 模板文件查找顺序:diy > current_theme > default_theme
214
- 6. 使用钩子系统时注意处理异步操作
307
+ 1. **依赖要求**: 需要安装 `art-template` 和 `mm_expand` 依赖包
308
+ 2. **目录权限**: 确保模板目录具有读写权限
309
+ 3. **缓存管理**: 及时清理过期缓存,避免内存泄漏
310
+ 4. **钩子优先级**: 数值越小优先级越高,执行顺序越靠前
311
+ 5. **异步处理**: 钩子函数支持异步操作,注意错误处理
312
+ 6. **文件查找**: 模板文件按优先级顺序查找,确保文件存在
313
+ 7. **字符转义**: 自动处理模板语法字符,避免冲突
314
+
315
+ ## 开发
316
+
317
+ ```bash
318
+ # 运行测试
319
+ npm test
320
+
321
+ # 查看代码覆盖率
322
+ npm run coverage
323
+ ```
215
324
 
216
325
  ## 许可证
217
326
 
218
- MIT
327
+ MIT License
package/README_EN.md ADDED
@@ -0,0 +1,327 @@
1
+ # mm_tpl
2
+
3
+ Super Meimei Template Engine Module, based on art-template engine, provides powerful MVC pattern view rendering functionality with hook system, theme switching, and caching mechanism.
4
+
5
+ [中文文档](README.md) | [English Documentation](README_EN.md)
6
+
7
+ ## Table of Contents
8
+
9
+ - [Features](#features)
10
+ - [Installation](#installation)
11
+ - [Quick Start](#quick-start)
12
+ - [Advanced Features](#advanced-features)
13
+ - [API Reference](#api-reference)
14
+ - [Notes](#notes)
15
+ - [Development](#development)
16
+ - [License](#license)
17
+
18
+ ## Features
19
+
20
+ - 🚀 High-performance template engine based on art-template
21
+ - 🔧 Support for multiple template syntax rules
22
+ - 🎨 Theme switching and template file priority search
23
+ - ⚡ Built-in caching mechanism for performance optimization
24
+ - 🔌 Powerful hook system support
25
+ - 📁 Flexible directory structure support
26
+ - 🛡️ Comprehensive error handling mechanism
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ npm install mm_tpl
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ### 1. Install Dependencies
37
+
38
+ ```bash
39
+ npm install mm_tpl
40
+ ```
41
+
42
+ ### 2. Initialize Template Engine
43
+
44
+ ```javascript
45
+ const {Tpl} = require('mm_tpl');
46
+
47
+ // Create template instance
48
+ const tpl = new Tpl({
49
+ root: process.cwd(), // Root directory
50
+ default_dir: "./template/", // Default template directory
51
+ default_theme: 'default', // Default theme
52
+ extname: ".html", // Template file extension
53
+ cache_root: './cache', // Cache directory
54
+ cache_extname: '.cache.html', // Cache file extension
55
+ rules: [nativeRule, artRule, htmlRule, jsRule, pyRule, pyRule2] // Template rules
56
+ });
57
+ ```
58
+
59
+ ### 3. Basic Template Rendering
60
+
61
+ ```javascript
62
+ // Simple variable substitution
63
+ const result = tpl.render("<div>${message}</div>", {
64
+ message: "Hello World"
65
+ });
66
+ // Output: <div>Hello World</div>
67
+
68
+ // Compile template function
69
+ const compiled = tpl.compile("<div>${name} - ${age}</div>");
70
+ const result2 = compiled({ name: "John", age: 25 });
71
+ // Output: <div>John - 25</div>
72
+ ```
73
+
74
+ ### 4. Loop Rendering
75
+
76
+ ```javascript
77
+ // Array loop
78
+ const arrayResult = tpl.render(`
79
+ <ul>
80
+ ${loop arr value idx}
81
+ <li>${idx}: ${value}</li>
82
+ ${/loop}
83
+ </ul>
84
+ `, {
85
+ arr: [123, 234]
86
+ });
87
+
88
+ // Object loop
89
+ const objectResult = tpl.render(`
90
+ <dl>
91
+ ${loop obj value key}
92
+ <dt>${key}</dt>
93
+ <dd>${value}</dd>
94
+ ${/loop}
95
+ </dl>
96
+ `, {
97
+ obj: { name: "John", age: 25 }
98
+ });
99
+
100
+ // Traditional for loop
101
+ const forResult = tpl.render(`
102
+ <ul>
103
+ <!--[ for(var i = 0; i < arr.length; i++){ ]-->
104
+ <li>${arr[i]}</li>
105
+ <!--[ } ]-->
106
+ </ul>
107
+ `, {
108
+ arr: [123, 234]
109
+ });
110
+
111
+ // Each loop
112
+ const eachResult = tpl.render(`
113
+ <ul>
114
+ ${each arr}
115
+ <li>${$value}</li>
116
+ ${/each}
117
+ </ul>
118
+ `, {
119
+ arr: [123, 234]
120
+ });
121
+ // Output:
122
+ // <ul>
123
+ // <li>123</li>
124
+ // <li>234</li>
125
+ // </ul>
126
+ ```
127
+
128
+ ### 5. View Rendering
129
+
130
+ ```javascript
131
+ // Set global variables
132
+ $.globalBag.siteName = "My Website";
133
+
134
+ // Set view variables
135
+ tpl.set({
136
+ title: "Homepage",
137
+ keywords: "keywords"
138
+ });
139
+
140
+ // Render view file
141
+ const html = tpl.view("./views/index.html", {
142
+ user: { name: "John" }
143
+ });
144
+ // Output: Rendering result <div>Hello World</div>
145
+
146
+ // Get view variable
147
+ const title = tpl.get("title");
148
+
149
+ // Delete view variable
150
+ tpl.del("keywords");
151
+ ```
152
+
153
+ ### 6. Caching Mechanism
154
+
155
+ ```javascript
156
+ // Use cache for view rendering
157
+ const html = tpl.view("./views/page", {
158
+ data: someData
159
+ }, {
160
+ cache: true, // Whether to use cache
161
+ cache_filename: "./cache" // Cache filename
162
+ });
163
+
164
+ // Clear cache
165
+ tpl.clearCache('./views/mall'); // Clear cache for specific directory
166
+ // or
167
+ tpl.clearCache(); // Clear all cache
168
+ ```
169
+
170
+ ### 7. Hook System
171
+
172
+ #### Add Function Hook
173
+ ```javascript
174
+ $.hook.addFunc('list', async function(viewBag, req, type) {
175
+ // Process list logic
176
+ var query = req.query;
177
+ if (query.user_id) {
178
+ viewBag.user_id = query.user_id;
179
+ }
180
+ return someData;
181
+ }, 100, 'listFunc'); // sort: priority, alias: alias
182
+ ```
183
+
184
+ #### Add Action Hook
185
+ ```javascript
186
+ $.hook.addAction('header', function(viewBag, param) {
187
+ return "<header>Website Header</header>";
188
+ }, 1, "headerAction");
189
+ ```
190
+
191
+ #### Add Filter Hook
192
+ ```javascript
193
+ $.hook.addFilter('content', function(viewBag, content, param) {
194
+ return content.replace("old text", "new text");
195
+ }, 1, "contentFilter");
196
+ ```
197
+
198
+ #### Execute Hooks
199
+ ```javascript
200
+ // Execute function hook
201
+ const result = await tpl.runFunc('list', { query: { page: 1 } }, 'article');
202
+
203
+ // Execute action hook
204
+ const actionResult = tpl.runHook('header', { param: 'value' });
205
+
206
+ // Use hooks in template
207
+ const html = tpl.render(`
208
+ <div>
209
+ ${hookAction('header')}
210
+ ${hookFilter('content', 'original content')}
211
+ </div>
212
+ `, data);
213
+ ```
214
+
215
+ #### Delete Hooks
216
+ ```javascript
217
+ // Delete specific hook
218
+ $.hook.delFunc('list', 'listFunc');
219
+ $.hook.delAction('header', 'headerAction');
220
+ $.hook.delFilter('content', 'contentFilter');
221
+
222
+ // Clear all hooks
223
+ $.hook.clear();
224
+ ```
225
+
226
+ ## Advanced Features
227
+
228
+ ### 1. Theme and Directory Support
229
+ ```javascript
230
+ // Set current theme
231
+ tpl.current_theme = "dark";
232
+
233
+ // Template file search order (priority from high to low):
234
+ // 1. diy directory (custom directory)
235
+ // 2. Current theme directory
236
+ // 3. Default theme directory
237
+ ```
238
+
239
+ ### 2. Template Rules
240
+ Built-in support for multiple template rules, including:
241
+ - nativeRule: Native syntax rules
242
+ - artRule: art-template syntax rules
243
+ - htmlRule: HTML comment syntax rules
244
+ - jsRule: JavaScript syntax rules
245
+ - pyRule: Python-style syntax rules
246
+
247
+ ### 3. Error Handling
248
+ ```javascript
249
+ const html = tpl.view("./template.html", data);
250
+ if (tpl.error) {
251
+ console.error("Rendering error:", tpl.error);
252
+ }
253
+ ```
254
+
255
+ ### 4. Character Escaping
256
+ ```javascript
257
+ // Automatically escape special characters
258
+ const escaped = tpl.escape("<div>${content}</div>");
259
+ // Output: <div>·$·{content}</div>
260
+
261
+ // Restore escaped characters
262
+ const restored = tpl.escape(escaped, true);
263
+ // Output: <div>${content}</div>
264
+ ```
265
+
266
+ ### 5. Global Mounting
267
+ ```javascript
268
+ // Automatically mount to global object
269
+ if (global.$ && !$.Tpl) {
270
+ $.Tpl = Tpl;
271
+ $.tpl = new Tpl();
272
+ }
273
+ ```
274
+
275
+ ## API Reference
276
+
277
+ ### Tpl Class Methods
278
+
279
+ - `constructor(config)` - Constructor, create template instance
280
+ - `setConfig(config)` - Set configuration parameters
281
+ - `render(body, model, options)` - Render template string
282
+ - `compile(body, options)` - Compile template to function
283
+ - `view(file, model, options)` - Render template file
284
+ - `set(obj)` - Set view data
285
+ - `get(key)` - Get view data
286
+ - `del(keys)` - Delete view data
287
+ - `clearCache(path, file)` - Clear cache
288
+ - `runFunc(name, req, ...args)` - Execute function hook
289
+ - `runHook(name, req, ...args)` - Execute action hook (alias of runFunc)
290
+ - `escape(body, restore)` - Escape/restore characters
291
+
292
+ ### Hook Class Methods
293
+
294
+ - `addFunc(name, func, sort, alias)` - Add function hook
295
+ - `addAction(name, func, sort, alias)` - Add action hook
296
+ - `addFilter(name, func, sort, alias)` - Add filter hook
297
+ - `runFunc(name, model, req, ...args)` - Execute function hook
298
+ - `runAction(name, model, ...args)` - Execute action hook
299
+ - `runFilter(name, model, ret, ...args)` - Execute filter hook
300
+ - `delFunc(name, alias)` - Delete function hook
301
+ - `delAction(name, alias)` - Delete action hook
302
+ - `delFilter(name, alias)` - Delete filter hook
303
+ - `clear(name)` - Clear hooks
304
+
305
+ ## Notes
306
+
307
+ 1. **Dependencies**: Requires `art-template` and `mm_expand` dependency packages
308
+ 2. **Directory Permissions**: Ensure template directories have read/write permissions
309
+ 3. **Cache Management**: Clean expired cache promptly to avoid memory leaks
310
+ 4. **Hook Priority**: Lower numerical values indicate higher priority and earlier execution
311
+ 5. **Async Processing**: Hook functions support async operations, pay attention to error handling
312
+ 6. **File Search**: Template files are searched in priority order, ensure files exist
313
+ 7. **Character Escaping**: Automatic handling of template syntax characters to avoid conflicts
314
+
315
+ ## Development
316
+
317
+ ```bash
318
+ # Run tests
319
+ npm test
320
+
321
+ # Check code coverage
322
+ npm run coverage
323
+ ```
324
+
325
+ ## License
326
+
327
+ MIT License
package/hook.js CHANGED
@@ -1,3 +1,4 @@
1
+
1
2
  const {
2
3
  types
3
4
  } = require("util");
@@ -55,7 +56,7 @@ Hook.prototype._getName = function (func, alias) {
55
56
  * @param {string} alias - 函数别名
56
57
  * @returns {string} 函数别名
57
58
  */
58
- Hook.prototype.addFunc = function (name, func, sort, alias) {
59
+ Hook.prototype.addFunc = function (name, func, sort = 100, alias = "") {
59
60
  alias = this._getName(func, alias);
60
61
  var obj = {
61
62
  func,
@@ -185,14 +186,16 @@ Hook.prototype.delFilter = function (name, alias = "") {
185
186
  Hook.prototype.runFunc = async function (name, model, req, ...args) {
186
187
  var ret;
187
188
  var list = this._func[name];
188
- if (!list) {
189
- var len = list.length;
190
- for (var i = 0; i < len; i++) {
189
+ if (list) {
190
+ for (var i = 0; i < list.length; i++) {
191
191
  var item = list[i];
192
192
  try {
193
- ret = item.func(model, req, ...args);
194
- if (ret) {
195
- ret = await ret;
193
+ var ret_new = item.func(model, req, ...args);
194
+ if (types.isPromise(ret_new)) {
195
+ ret_new = await ret_new;
196
+ if (ret_new) {
197
+ ret = ret_new;
198
+ }
196
199
  }
197
200
  } catch (err) {
198
201
  $.log.error(`[${this.constructor.name}] 执行函数钩子失败 ${item.alias}`, err);
@@ -235,9 +238,8 @@ Hook.prototype.runAction = function (name, model, ...args) {
235
238
  */
236
239
  Hook.prototype.runFilter = function (name, model, ret, ...args) {
237
240
  var list = this._filter[name];
238
- if (!list) {
239
- var len = list.length;
240
- for (var i = 0; i < len; i++) {
241
+ if (list) {
242
+ for (var i = 0; i < list.length; i++) {
241
243
  var item = list[i];
242
244
  try {
243
245
  ret = item.func(model, ret, ...args) || ret;
package/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  const template = require('art-template');
2
- const Hook = require('./hook.js');
3
2
  const {
4
3
  Base
5
4
  } = require('mm_expand');
5
+ const Hook = require('./hook.js');
6
6
  const {
7
7
  nativeRule,
8
8
  artRule,
@@ -346,17 +346,17 @@ Tpl.prototype.view = function (file, model, options) {
346
346
  if (file.replace('./', '').indexOf('.') === -1 && !file.endsWith(this.config.extname)) {
347
347
  file += this.config.extname;
348
348
  }
349
- var f = file.fullname(this.dir + 'diy');
349
+ var f = file.fullname('diy'.fullname(this.dir));
350
350
  if (!f.hasFile()) {
351
- f = file.fullname(this.config.default_dir + 'diy');
351
+ f = file.fullname('diy'.fullname(this.config.default_dir));
352
352
  if (!f.hasFile()) {
353
- f = file.fullname(this.dir + this.current_theme);
353
+ f = file.fullname(this.current_theme.fullname(this.dir));
354
354
  if (!f.hasFile()) {
355
- f = file.fullname(this.dir + this.config.default_theme);
355
+ f = file.fullname(this.config.default_theme.fullname(this.dir));
356
356
  if (!f.hasFile()) {
357
- f = file.fullname(this.config.default_dir + this.current_theme);
357
+ f = file.fullname(this.current_theme.fullname(this.config.default_dir));
358
358
  if (!f.hasFile()) {
359
- f = file.fullname(this.config.default_dir + this.config.default_theme);
359
+ f = file.fullname(this.config.default_theme.fullname(this.config.default_dir));
360
360
  }
361
361
  }
362
362
  }
@@ -369,15 +369,16 @@ Tpl.prototype.view = function (file, model, options) {
369
369
  message: f + "文件不存在!"
370
370
  }
371
371
  }
372
- var body = f.loadText();
373
- if (body) {
374
- body = this.escape(body);
375
- body = this._renderSub(body, model, options);
376
- body = this.escape(body, true);
377
- return body;
378
- } else {
379
- return "";
372
+ else {
373
+ var body = f.loadText();
374
+ if (body) {
375
+ body = this.escape(body);
376
+ body = this._renderSub(body, model, options);
377
+ body = this.escape(body, true);
378
+ return body;
379
+ }
380
380
  }
381
+ return "";
381
382
  };
382
383
 
383
384
  /**
@@ -431,7 +432,7 @@ Tpl.prototype.clearCache = function (path, file) {
431
432
  });
432
433
  };
433
434
 
434
- if (global.$ && !global.$.Tpl) {
435
+ if (global.$ && !$.Tpl) {
435
436
  $.Tpl = Tpl;
436
437
  $.tpl = new Tpl();
437
438
  }
package/package.json CHANGED
@@ -1,27 +1,33 @@
1
1
  {
2
2
  "name": "mm_tpl",
3
- "version": "2.4.5",
4
- "description": "这是超级美眉模板帮助类模块,用于MVC模式下的视图渲染",
3
+ "version": "2.4.7",
4
+ "description": "Super Meimei Template Engine - High-performance template engine based on art-template with MVC pattern, hook system, theme switching and caching mechanism",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "dev": "nodemon test.js",
8
- "test": "node test.js"
8
+ "test": "node test.js",
9
+ "coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage"
9
10
  },
10
11
  "repository": {
11
12
  "type": "git",
12
13
  "url": "git+https://gitee.com/qiuwenwu91/mm_tpl.git"
13
14
  },
14
15
  "keywords": [
16
+ "template",
17
+ "engine",
15
18
  "mvc",
16
19
  "web",
17
20
  "view",
18
- "model",
19
- "controller",
20
21
  "render",
21
- "template"
22
+ "art-template",
23
+ "hook",
24
+ "theme",
25
+ "cache",
26
+ "nodejs",
27
+ "javascript"
22
28
  ],
23
29
  "author": "邱文武",
24
- "license": "ISC",
30
+ "license": "MIT",
25
31
  "bugs": {
26
32
  "url": "https://gitee.com/qiuwenwu91/mm_tpl/issues"
27
33
  },
@@ -29,5 +35,16 @@
29
35
  "dependencies": {
30
36
  "art-template": "^4.13.4",
31
37
  "mm_expand": "^1.9.7"
32
- }
38
+ },
39
+ "engines": {
40
+ "node": ">=12.0.0"
41
+ },
42
+ "files": [
43
+ "index.js",
44
+ "hook.js",
45
+ "tpl_rule.js",
46
+ "README.md",
47
+ "README_EN.md",
48
+ "package.json"
49
+ ]
33
50
  }
package/.gitattributes DELETED
@@ -1,5 +0,0 @@
1
- # Auto detect text files and perform LF normalization
2
- * text=auto
3
- *.js linguist-language=JavaScript
4
- *.css linguist-language=JavaScript
5
- *.html linguist-language=JavaScript
@@ -1,30 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>超级美眉Art模板引擎</title>
6
- </head>
7
- <body>
8
- <h5>系统名称</h5>
9
- <p>你真的是人才!</p>
10
- <p>你真的是人才!</p>
11
- <ul>
12
- <li>\·$·{· value }</li>
13
- <li>\·$·{· value }</li>
14
- </ul>
15
- <ul>
16
- <li>123</li>
17
- <li>234</li>
18
- </ul>
19
- <ul>
20
- <li>123</li>
21
- <li>234</li>
22
- </ul>
23
- <strong>hello world!</strong>
24
- <script type="text/javascript">
25
- var a_0 =123;
26
- var a_1 =234;
27
- </script>系统名称计算
28
- 123123'priceNIHAO'#计算
29
- </body>
30
- </html>
@@ -1,36 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>${globalBag.name}</title>
6
- </head>
7
- <body>
8
- <h5>${viewBag.name}</h5>
9
- <ul>
10
- ${loop arr value idx}
11
- <li>${ value }</li>
12
- ${/loop}
13
- </ul>
14
- <ul>
15
- <!--[ for(var i = 0; i < arr.length; i++) { ]-->
16
- <li>${ arr[i] }</li>
17
- <!--[ } ]-->
18
- </ul>
19
- <ul>
20
- <!--{loop arr value idx}-->
21
- <li>${ value }</li>
22
- <!--{/loop}-->
23
- </ul>
24
- <script type="text/javascript">
25
- /*[loop arr value idx]*/
26
- var a_${idx} = ${value};
27
- /*[/loop]*/
28
- </script>
29
- ${viewBag.name}
30
- ## "计算" ##
31
- 123123'"""#
32
- "price" + "NIHAO"
33
- #"""'
34
- ## "#计算" ##
35
- </body>
36
- </html>
@@ -1,36 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>${globalBag.name}</title>
6
- </head>
7
- <body>
8
- <h5>${viewBag.name}</h5>
9
- <ul>
10
- ${loop arr value idx}
11
- <li>${ value }</li>
12
- ${/loop}
13
- </ul>
14
- <ul>
15
- <!--[ for(var i = 0; i < arr.length; i++) { ]-->
16
- <li>${ arr[i] }</li>
17
- <!--[ } ]-->
18
- </ul>
19
- <ul>
20
- <!--{loop arr value idx}-->
21
- <li>${ value }</li>
22
- <!--{/loop}-->
23
- </ul>
24
- <script type="text/javascript">
25
- /*[loop arr value idx]*/
26
- var a_${idx} = ${value};
27
- /*[/loop]*/
28
- </script>
29
- ${viewBag.name}
30
- ## "计算" ##
31
- 123123'"""#
32
- "price" + "NIHAO"
33
- #"""'
34
- ## "#计算" ##
35
- </body>
36
- </html>
@@ -1,39 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>${globalBag.name}</title>
6
- </head>
7
- <body>
8
- <h5>${viewBag.name}</h5>
9
- <p>${@hookFilter('test', '你真的是人才!')}</p>
10
- <p><!--{@hookFilter('test', '你真的是人才!', {key: '123'})}--></p>
11
- <ul>
12
- ${loop arr value idx}
13
- <li>\${ value }</li>
14
- ${/loop}
15
- </ul>
16
- <ul>
17
- <!--[ for(var i = 0; i < arr.length; i++) { ]-->
18
- <li>${ arr[i] }</li>
19
- <!--[ } ]-->
20
- </ul>
21
- <ul>
22
- <!--{loop arr value idx}-->
23
- <li>${ value }</li>
24
- <!--{/loop}-->
25
- </ul>
26
- <strong>${message}</strong>
27
- <script type="text/javascript">
28
- /*[loop arr value idx]*/
29
- var a_${idx} = ${value};
30
- /*[/loop]*/
31
- </script>
32
- ${viewBag.name}
33
- ## "计算" ##
34
- 123123'"""#
35
- "price" + "NIHAO"
36
- #"""'
37
- ## "#计算" ##
38
- </body>
39
- </html>
@@ -1,13 +0,0 @@
1
- <div class="bar_user">
2
- ${@hookFilter('test', hook_action('test', '好的'), '真的')}
3
- <div>用户ID:${viewBag.user_id}</div>
4
- <div>当前项目ID:${viewBag.project_id}</div>
5
- <div>${message}</div>
6
- </div>
7
-
8
- <div class="bar">导航栏</div>
9
- <style>
10
- .bar {
11
- font-weight: 800;
12
- }
13
- </style>
@@ -1,11 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>${globalBag.name}</title>
6
- </head>
7
- <body>
8
- <div>游戏主题</div>
9
- <div>${@view('./bar.html')}</div>
10
- </body>
11
- </html>
package/test.js DELETED
@@ -1,133 +0,0 @@
1
- const {Tpl} = require('./index.js');
2
-
3
- /**
4
- * 基础模板渲染测试函数
5
- * 演示简单的变量替换功能
6
- * @async
7
- */
8
- async function test() {
9
- var tpl = new Tpl();
10
- var body = tpl.render("<a>${test} + 123123</a>", {
11
- test: 123
12
- });
13
- $.log.debug(body);
14
- }
15
-
16
- /**
17
- * 数组/对象循环渲染测试函数
18
- * 演示模板中的循环功能
19
- * @async
20
- */
21
- async function test() {
22
- var tpl = new Tpl();
23
- // 数组循环示例
24
- // var body = tpl.render("<a>${loop arr value idx} ${idx} ${ value } ${/loop} + 123123</a>", { arr: [123,234] });
25
-
26
- // 对象循环示例
27
- var body = tpl.render("<a>${ loop obj value key } ${ key } ${ value } ${/loop} + 123123</a>", { obj: { a: 123, b: 467 } });
28
-
29
- // 传统for循环示例
30
- // var body = tpl.render("<a><!--[ for(var i = 0; i < arr.length; i++){ ]--> ${ arr[i] } <!--[ } ]--> + 123123</a>", {
31
- // arr: [123, 234]
32
- // });
33
-
34
- // each循环示例
35
- // var body = tpl.render("<a>${ each arr } ${ arr[$index] } ${/each} + 123123</a>", { arr: [123,234] });
36
- // var view = tpl.render("<a>${ each arr } ${ $value } ${/each} + 123123</a>", { arr: [123,234] });
37
- $.log.debug(body);
38
- }
39
-
40
- /**
41
- * 模板视图渲染测试函数
42
- * 演示全局变量和视图渲染的使用
43
- * @async
44
- */
45
- async function test() {
46
- $.log.debug("测试开始")
47
- var tpl = new Tpl();
48
- // 设置全局变量
49
- $.globalBag.name = "超级美眉Art模板引擎";
50
-
51
- // 设置实例视图变量
52
- tpl.viewBag.name = "系统名称";
53
-
54
- // 渲染视图
55
- var body = tpl.view("./test.html", { arr: [123,234] });
56
- $.log.debug(tpl.error);
57
- $.log.debug(body);
58
- }
59
-
60
- /**
61
- * 钩子和动作测试函数
62
- * 演示带有动作和过滤器的钩子系统
63
- * @async
64
- */
65
- async function test() {
66
- var tpl = new Tpl();
67
-
68
- // 设置全局变量
69
- $.globalBag.name = "超级美眉Art模板引擎";
70
-
71
- // 设置实例视图变量
72
- tpl.viewBag.name = "系统名称";
73
- tpl.current_theme = "game";
74
- tpl.dir = "";
75
-
76
- // 添加列表函数钩子
77
- $.hook.addFunc('list', async function(m, req, type) {
78
- console.log("参数", m, req, type);
79
- var query = req.query;
80
- if (query.user_id) {
81
- m.user_id = query.user_id;
82
- }
83
- if (query.project_id) {
84
- m.project_id = query.project_id;
85
- }
86
- $.log.debug("列表", m);
87
- });
88
-
89
- // 添加动作钩子
90
- $.hook.addAction('test', function aa(m, param) {
91
- return "<div>你好吗?</div>";
92
- }, 2);
93
-
94
- $.hook.addAction('test', function(m, param) {
95
- return "<div>你好!}</div>";
96
- }, 1, "测试动作1");
97
-
98
- // 添加过滤器钩子
99
- $.hook.addFilter('test', function(m, ret, param) {
100
- $.log.debug("测试", ret);
101
- return ret.replace("你", "您");
102
- }, 1, "测试过滤");
103
-
104
- // 删除动作钩子
105
- $.hook.delAction('test', "aa");
106
- $.hook.delAction('test', "测试动作1");
107
- // $.hook.delFilter('test', "测试过滤");
108
-
109
- // 运行函数钩子
110
- await tpl.runFunc('list', {
111
- query: {
112
- user_id: 1,
113
- project_id: 2
114
- }
115
- }, 'article');
116
-
117
- // 使用缓存渲染视图
118
- var body = tpl.view("./ad", {
119
- arr: [123, 234],
120
- message: "hello world!"
121
- }, {
122
- // 是否读取缓存文件,如果为false但有cache_filename,则只保存缓存但不读取
123
- cache: false,
124
- // 缓存文件名
125
- cache_filename: "./test"
126
- });
127
- // 删除指定目录下的缓存文件
128
- // tpl.clear_cache('./mall');
129
- $.log.debug("渲染结果", body);
130
- }
131
-
132
- // 执行测试
133
- test();