[英]How to compile doT.js partials from a file into a string?
嗨,我是node的新手,我想弄清楚如何使用doT.js( http://olado.github.io/doT/index.html )將文件中的部分內容編譯成字符串。
/controllers/system/index.js:
var util = require( 'util' ),
fs = require( 'fs' ),
dot = require( 'dot' );
function System( ) {
this.name = 'system';
}
System.prototype._loadFile = function( path, def ) {
var def = def || { },
tpl, str;
str = fs.readFileSync( process.argv[ 1 ].replace( /\/[^\/]*$/, path ) );
tpl = dot.compile( str );
str = tpl( def );
return str;
};
System.prototype._getHeaderContent = function( ) {
return this._loadFile( '/controllers/system/views/header.html', {
name: this.name
});
};
System.prototype._getBodyContent = function( ) {
return this._loadFile( '/controllers/system/views/main.html' );
};
System.prototype._getFooterContent = function( ) {
return this._loadFile( '/controllers/system/views/footer.html' );
};
System.prototype.index = function( req, res, next ) {
res.render( __dirname + '/../system/views/template', {
header: this._getHeaderContent( ),
body: this._getBodyContent( ),
footer: this._getFooterContent( )
});
next ? next( ) : '';
};
module.exports = System;
/controllers/system/views/template.html:
{{=it.header}}
{{=it.body}}
{{=it.footer}}
/controllers/system/views/header.html:
<!doctype html>
<html lang="en">
<head>
<title>app | {{=it.name}}</title>
</head>
<body>
在System.index中,當我調用res.render template.html時,正在編譯,而header.html不是。 據此,我認為render不會遞歸地渲染文件,因此我需要先手動編譯header.html,然后再將其傳遞給res.render。
我找到了本教程: http ://olado.github.io/doT/tutorial.html#compile但是.template和.compile返回函數? 嘗試將它們傳遞給res.render會引發錯誤。
如何將它們編譯成字符串? 還是我走錯路了?
謝謝!
更新-使用工作代碼進行了固定和更新,感謝Andreas Hultgren!
dot.compile()
或dot.template()
從模板字符串返回已編譯的函數。 在有或沒有數據的情況下都調用它( compiledTemplate(data)
)以將生成的模板作為字符串獲取。 附帶說明,大多數模板引擎都是以這種方式工作的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.