Handlebars自定义,如果helper else未定义 [英] Handlebars custom if helper else is undefined
本文介绍了Handlebars自定义,如果helper else未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Handlebars.registerHelper('hasAccess',function(val,fnTrue, fnFalse){
return val> 5?fnTrue():fnFalse();
});
以及我的模板,如下所示:
{{#hasAccess this.access}}
您有权限访问!
{{else}}
您无权访问
{{/ hasAccess}}
它有效,但fnFalse未定义。所以,我该如何渲染'else'分支?
解决方案
Handlebars提供了一个包含不同函数的对象应用 options.fn
和 options.inverse
。请参阅 http://handlebarsjs.com/block_helpers.html#conditionals
您的帮手可以写成:
$ b
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>&
登录 关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆