2013-02-26 91 views

回答

2

是的。你可以建立一個函數在加載時被執行(即在明確的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(); 
+0

感謝您的示例。我找到了express.compile中間件。 app.use(express.compiler({src:__dirname +'/ public',enable:['less']})); (express.static(__ dirname +'/ public')); 這是我的問題嗎? – Erik 2013-02-26 16:36:46