0
我有一個nodejs/express應用程序。我爲我的模板使用了玉石模板系統。當我得到模板時,它每次都進行組裝。但我想通過編譯來提高性能。是否可以表達?是否有可能爲生產用途編譯玉石模板?
我有一個nodejs/express應用程序。我爲我的模板使用了玉石模板系統。當我得到模板時,它每次都進行組裝。但我想通過編譯來提高性能。是否可以表達?是否有可能爲生產用途編譯玉石模板?
是的。你可以建立一個函數在加載時被執行(即在明確的app
聲明),這將編譯所有的模板,並留在他們的記憶:
拿這個作爲一個例子:
/**
* @param {Object} app
*
* @api private
*
* @summary Compiles the partial dashboard templates into memory
* enabling the admin controller to send partial HTMLs
*/
function compileJadeTemplates (app) {
var templatesDir = path.resolve(
app.get('views')
, 'partials'
);
var templateFiles
, fn
, compiledTemplates = {};
try {
templateFiles = fs.readdirSync(templatesDir);
for (var i in templateFiles) {
fn = jade.compile(
fs.readFileSync(path.resolve(templatesDir, templateFiles[i])));
compiledTemplates[templateFiles[i]] = fn;
}
app.set('dashboard-templates', compiledTemplates);
} catch (e) {
console.log('ERROR');
console.log('---------------------------------------');
console.log(e);
throw 'Error on reading dashboard partials directory!';
}
return app;
}
這樣調用模板的expressJS控制器功能:
/**
* @param {String} req
* @param {Object} res
* @param {Object} next
*
* @api public
*
* @url GET /admin/dashboard/user_new
*
* @summary Returns HTML via AJAX for user creation
*/
controller.newUser = function (req, res, next) {
var compiledTemplates = app.get('dashboard-templates');
var html = compiledTemplates['_user_new.jade']({ csrf : req.session._csrf});
return res.send({ status : 'OK', message : html});
}
在這種情況下,我要送通過AJAX html
;由申請附加。如果你不想這樣做。您可以發送這些功能的HTML:
res.write(html);
return res.end();
感謝您的示例。我找到了express.compile中間件。 app.use(express.compiler({src:__dirname +'/ public',enable:['less']})); (express.static(__ dirname +'/ public')); 這是我的問題嗎? – Erik 2013-02-26 16:36:46