所以我想将ejs模板预编译成.js文件
var compiled = ejs.compile(source);
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled);
Run Code Online (Sandbox Code Playgroud)
但是这可以成为
function (locals){
return fn.call(this, locals, filters, utils.escape);
}
Run Code Online (Sandbox Code Playgroud)
什么是预编译和编写ejs模板到.js文件的最佳方法
您可以创建 templates.js 文件(手动或在代码中)作为空模块。然后编译模板后,将编译后的函数附加到空模块上。
var ejs = require('ejs');
var fs = require('fs');
fs.writeFileSync('./template.js', 'module.exports = { }', 'utf8');
var compiled = ejs.compile(fs.readFileSync('./example.ejs', 'utf8'));
// Add an example function to the template file that uses the compiled function
require('./template').example = compiled;
// Get the example template again (this could be in another file for example)
var output = require('./template').example;
var html = output({ id: 10, title: 'Output' });
Run Code Online (Sandbox Code Playgroud)
由于默认情况下会缓存模块,因此您应该能够require('./template.js')在任何需要的地方进行操作,并且它将附加所有预编译模板。
| 归档时间: |
|
| 查看次数: |
2460 次 |
| 最近记录: |