【问题标题】:how do you precompile ejs templates to file你如何预编译 ejs 模板到文件
【发布时间】:2012-07-20 07:20:59
【问题描述】:

所以我想将 ejs 模板预编译成 .js 文件

var compiled = ejs.compile(source);
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled);

但这会变成

function (locals){
   return fn.call(this, locals, filters, utils.escape);
}

预编译 ejs 模板并将其写入 .js 文件的最佳方法是什么

【问题讨论】:

    标签: ejs


    【解决方案1】:

    您可以将 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' });
    

    由于默认情况下modules are cached,你应该可以在任何你需要的地方require('./template.js'),它会附上所有的预编译模板。

    【讨论】:

    • 这与序列化模板无关,这是实际问题。
    【解决方案2】:

    Lodash _.template() 方法在编译期间创建 EJS 模板函数的字符串表示,并将其作为 source 属性附加到编译后的函数。您可以将该字符串存储到 JS 文件中,将其嵌入到 HTML 中,或者在睡觉前将其读给您的孙子孙女。

    例如:

    > var _ = require('lodash');
    > var compiled = _.template('Hi <%= user %>!');
    > compiled({ user: 'Axel' })
    "Hi Axel!"
    > compiled.source
    "function(obj) {
      obj || (obj = {});
      var __t, __p = '';
      with (obj) {
        __p += 'Hi' + ((__t = ( user )) == null ? '' : __t) + '!';
      }
      return __p
    }"
    > var fs = require('fs')
    > var src = 'module.exports = ' + compiled.source;
    > fs.writeFileSync('mylittlescript.js', src);
    

    这种方法被 Webpack 的 ejs-loader 模块使用。另请注意,npm 包 ejs 不提供此类 source 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      相关资源
      最近更新 更多