15

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

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”分支?

4

1 回答 1

41

Handlebars 为自定义助手提供了一个对象,其中包含要应用的不同功能,options.fn并且options.inverse. 请参阅https://handlebarsjs.com/guide/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>

于 2012-07-04T11:10:04.713 回答