Viewer.js 2.12 KB
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;