Handlebars custom if helper else is undefined

前端 未结 1 1422
迷失自我
迷失自我 2021-02-07 15:35

I have a custom helper, as follows:

Handlebars.registerHelper(\'hasAccess\', function(val, fnTrue, fnFalse) { 
    return val > 5 ? fnTrue() : fnFalse();
});
         


        
1条回答
  •  旧巷少年郎
    2021-02-07 16:10

    Handlebars provides custom helpers an object containing the different functions to apply, options.fn and options.inverse. See https://handlebarsjs.com/guide/block-helpers.html#conditionals

    Your helper could be written as

    Handlebars.registerHelper('hasAccess', function(val, options) {
        var fnTrue = options.fn, 
            fnFalse = options.inverse;
    
        return val > 5 ? fnTrue(this) : fnFalse(this);
    });
    

    And a demo

    Handlebars.registerHelper('hasAccess', function(val, options) { 
        var fnTrue = options.fn, 
            fnFalse = options.inverse;
            
        return val > 5 ? fnTrue() : fnFalse();
    });
    
    var template = Handlebars.compile($('#tpl').html() );
    $("body").append( "

    access : 1

    " ); $("body").append( template({access:1}) ); $("body").append( "

    access : 6

    " ); $("body").append( template({access:6}) );
    
    
    
    

    0 讨论(0)
提交回复
热议问题