Viewer.js
2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var fs = require('fs');
var path=require('path');
var util = require('util');
var md5 = require('md5');
var Emitter=require('events');
/*重写控制器*/
var Viewer=function(app,tempEngine){
this.tempEngine=tempEngine;
this.cache={};
this.overrideExp(app);
this.engine=this.overrideEngine.bind(this);
Emitter.call(this);
};
util.inherits(Viewer,Emitter);
Viewer.prototype.overrideExp=function(app){
app.render=(function(render){
return function(view, options, callback) {
if(typeof options=="function"){
callback=options;
options={};
}
var views=view.split('.');
var _module=views.shift();
var filePath=path.resolve(global.apps,_module,"views/"+views.join('/'));
return render.call(this, filePath, options, callback);
};
})(app.render);
}
var __parsefile = function(fileKey,filePath,dataModel,callback){
var me=this,cache=this.cache;
/*判断catch 是否存在*/
var template = cache[fileKey];
if(template){
return callback(null,template(dataModel))
}
/*如果catch不存在就去读取 file*/
fs.readFile(filePath, 'utf8', function(err, str){
if(err){
return callback(err);
}
/*需要排除<!--{{}}-->*/
if(/\{\{>[^}]*\}\}/g.test(str)){
str=__parseLayout(filePath,str);
}
template =me.tempEngine.compile(str);
cache[fileKey]=template;
try{
var res = template(dataModel);
/*注册*/
return callback(null,res);
}
catch(err){
err.message = filePath + ': ' + err.message;
return callback(null,err.message);
}
});
}
var __parseLayout=function(form,str){
var layouts=str.match(/\{\{>[^}]*\}\}/g);
return str.replace(/\{\{>[^}]*\}\}/g,function($0){
var name=path.resolve(path.dirname(form),$0.match(/\{\{>\s*([^}]*)\s*\}\}/m)[1].replace(/\s/g,'')+".html");
var html=fs.readFileSync(name,'utf8');
if(/\{\{>[^}]*\}\}/g.test(html)){
html=__parseLayout(name,html);
}
return html;
});
}
Viewer.prototype.overrideEngine=function(filepath, options, callback){
var me=this,cache=this.cache;
/*每一个文件对应一个Key*/
var fileKey=md5(filepath),args=[].slice.call(arguments, 0);
return __parsefile.apply(this,[fileKey].concat(args));
}
module.exports= Viewer;