代码之家  ›  专栏  ›  技术社区  ›  Joe1992

注册Custom Helper Express和HBS

  •  2
  • Joe1992  · 技术社区  · 10 年前

    我是一个完全的Node菜鸟,所以请容忍我。

    我使用带有-hbs标志的expressgenerator模块将默认模板引擎切换为handlebar。

    我现在正在尝试注册一个自定义助手,以允许我向布局模板中的元素添加页面特定内容。

    我找不到我应该在哪里注册自定义hbs助手: 我用以下代码尝试了“.\node_modules\handlebars\dist\cjs\handlebar\compiler\helpers.js”(我在这里找到了: http://www.apkapps.link/questions/2420017/handlebars-with-express-different-html-head-for-different-pages ):

    function section(name, options){
            if(!this._sections) this._sections = {};
            this._sections[name] = options.fn(this);
            return null;
        }
    
    exports.section = section;
    

    但当我尝试从模板调用助手时,我会得到一个“缺少助手:'节'”

    有人能告诉我正确的方向吗?

    1 回复  |  直到 10 年前
        1
  •  6
  •   Rajan Panneer Selvam    10 年前

    从Handlebar的文档中,您必须将助手注册为,

    var hbs = require('hbs');
    
    hbs.registerHelper('helper_name', function(...) { ... });
    hbs.registerPartial('partial_name', 'partial value');
    

    您不需要修改“.\node_modules\handlebars\dist\cjs\handlebars/compiler\helpers.js

    推荐文章