Handlebars custom if helper else is undefined

China☆狼群 提交于 2019-12-04 10:44:19

问题


I have a custom helper, as follows:

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

and my template, as follows:

{{#hasAccess this.access}}
    You have access!
{{else}}
    You do not have access
{{/hasAccess}}

It works, except fnFalse is undefined. So, how am I supposed to render the 'else' branch?


回答1:


Handlebars provides custom helpers an object containing the different functions to apply, options.fn and options.inverse. See http://handlebarsjs.com/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( "<h1>access : 1</h1>" );
$("body").append( template({access:1}) );

$("body").append( "<h1>access : 6</h1>" );
$("body").append( template({access:6}) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>

<script type='text/template' id='tpl'>
{{#hasAccess this.access}}
    You have access!
{{else}}
    You do not have access
{{/hasAccess}}
</script>


来源:https://stackoverflow.com/questions/11327617/handlebars-custom-if-helper-else-is-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!