Express-hbs:带有选项/属性的异步Helper

Express-hbs: Asynchronous Helper with options/attrs

本文关键字:属性 异步 Helper 选项 Express-hbs      更新时间:2023-09-26

我正在使用express-hbs和Async helper,但我需要将选项发送到helper,但Async helper不支持此功能(或者我不知道如何)。正如你所看到的(下面的代码),我试图加载一个ADS助手/组件,但我需要发送额外的信息/属性来渲染基于方向和尺寸。

JavaScript

hbs.registerAsyncHelper( 'ads', function(filename, cb, options) {
       // options: is undefined
      // LOAD ADS FROM REMOVE SERVER.
       cb( new hbs.SafeString( ' == ADS  == ' ) );
});

HTML

{{{ads'page-x', 'vertical', '256x56' }}
有人能帮我解决这个问题吗?谢谢你!

简短的回答是,您目前(v0.7.10)只能在express-hbs中提供一个参数。

我能想到的唯一解决方法是使用JSON字符串作为参数,然后使用JSON.parse()在您的辅助函数中再次获得它们。

例如:

hbs.registerAsyncHelper( 'ads', function(arg, cb) {
    var options  = JSON.parse(arg);
    console.log(options);
    // LOAD ADS FROM REMOVE SERVER.
    cb( new hbs.SafeString( ' == ADS  == ' ) );
});

{{{ads "['"page-x'",'"vertical'",'"256x56'"]" }}}

express-hbs中出现多个参数问题的原因:

tl,博士

express-hbs registerAsyncHelper代码:

ExpressHbs.prototype.registerAsyncHelper = function(name, fn) {
    this.handlebars.registerHelper(name, function(context) {
        return async.resolve(fn.bind(this), context);
    });
};

只向车把注册一个参数(context)。但是handlebars将使用每个提供的参数作为额外参数调用注册的helper。所以注册函数应该是这样的:

ExpressHbs.prototype.registerAsyncHelper = function(name, fn) {
    this.handlebars.registerHelper(name, function(contextArgs) {
        return async.resolve(fn.bind(this), Array.prototype.slice.call(contextArgs));
    });
};

,但这也需要改变resolve函数。所以你必须等待修复或者自己修复,我猜。

正如你的问题下面的评论中提到的,在车把栏中多个参数的正确语法是不使用逗号。所以你的模板应该像这样(当handlebars-hbs是固定的):

{{{ads 'page-x' 'vertical' '256x56'}}}