如果辅助其他未定义,则自定义把手

时间:2012-07-04 10:51:26

标签: handlebars.js

我有一个自定义助手,如下所示:

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

和我的模板如下:

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

它有效,但fnFalse未定义。那么,我该怎么渲染'else'分支?

1 个答案:

答案 0 :(得分:34)

Handlebars为自定义助手提供了一个对象,其中包含要应用的不同功能,options.fnoptions.inverse。见http://handlebarsjs.com/block_helpers.html#conditionals

您的助手可以写成

Handlebars.registerHelper('hasAccess', function(val, options) {
    var fnTrue = options.fn, 
        fnFalse = options.inverse;

    return val > 5 ? fnTrue(this) : fnFalse(this);
});

和演示

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>