【问题标题】:Loading pre-compiled Handlebar templates in Node JS server side在 Node JS 服务器端加载预编译的 Handlebar 模板
【发布时间】:2015-04-04 01:25:03
【问题描述】:

是否有使用 handlebars.js NPM 模块加载预编译模板的协议,或者必须提供自己的“getTemplate”函数来加载特定模板?

以下失败,无法读取未定义的属性“你好”。

var compiledTemplate =  handlebars.templates['hello'];

“hello.handlebars”是模板文件的名称。

而这个工作正常。

var template = fs.readFileSync(“./hello.html", "utf8");
var uncompiledTemplate = handlebars.compile(template); 
var data = {message : "Hello world!"};
var finalPageHTML = uncompiledTemplate(data);

那么我需要什么才能执行

compiledTemplate(data) 

让我的最终 HTML 类似于未编译的版本?

谢谢。

【问题讨论】:

    标签: javascript node.js httphandler


    【解决方案1】:

    我找到了适合我的解决方案。我的模板目录中有一个模板,名为 list.handlebars:

    <ul>
        <li>{{title}}</li>
    </ul>
    

    然后,我运行这个命令:

    handlebars -c handlebars templates -f dist/templates.js && echo module.exports = templates; >> dist/templates.js
    

    '-c handlebars' 标志位于 require("handlebars");到输出。

    然后,在我的服务器代码中,我使用:

    var template = require('./dist/templates');
    console.log(template['list']({title: 'winner'}));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 2013-03-26
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2012-03-14
      相关资源
      最近更新 更多