在车把调用助手里如果块模板
我与Handlebars.js模板引擎的工作,我试图想出一个办法做这样的事情(人为的例子):在车把调用助手里如果块模板
{{#if itemSelected "SomeItem"}}
<div>This was selected</div>
{{/if}
其中itemSelected
是注册助手这样的:
Handlebars.registerHelper("itemSelected", function(item) {
var selected = false;
// Lots of logic that determines if item is selected
return selected;
});
尝试使用此语法模板时,我得到错误,我找不到出这种事情任何例子。我确实看到这样简单的#if块...
{{#if myValueInContext}}
<div>This will show if myValueInContext results in a truthy value.</div>
{{/if}}
但是,我无法弄清楚如何解决第一个例子。也许我正在接近这个错误。
顺便说一句,我标记了这个胡子,因为我不能添加一个Handlebars标签的问题。
我不认为这是行得通的。如果我理解handlebars文档是正确的,#if是一个已注册的block-helper,并且不会将另一个注册的helper作为参数。
根据文档,你可能会实现它像
Handlebars.registerHelper('ifItemSelected', function(item, block) {
var selected = false;
// lots of logic that determines if item is selected
if(selected) {
return block(this);
}
});
之后,你应该能够
{{#ifItemSelected SomeItem}}
This was selected
{{/ifItemSelected}
称呼它,但你必须确保SomeItem有正确的格式。我没有看到在if语句中使用注册处理程序作为条件的方法。
完美。这很好。谢谢! – Kevin 2011-06-14 01:16:08
@ gnowoel的答案可能更适合现代Handlebars – 2017-05-26 18:07:32
随着把手的最后一个版本(1.0.rc.1),你必须写某事喜欢:
Handlebars.registerHelper('ifItemSelected', function(item, options) {
var selected = false;
// lots of logic that determines if item is selected
if (selected) {
return options.fn(this);
}
});
即。
Handlebars.registerHelper('ifItemSelected', function(item, options) {
var selected = false;
// lots of logic that determines if item is selected
if (selected) {
return options.fn(this);
}
else {
return options.inverse(this);
}
});
使用:块(这)由options.fn(本)
截至最新Handlebars版本,这应该是公认的答案 – 2013-07-12 19:37:58
如果你想有一个别的选项过多,你将会需要此代码代替与:
{{#ifItemSelected SomeItem}}
This was selected
{{else}}
This was not selected
{{/ifItemSelected}
你应该在嵌入的助手invocat周围添加圆括号离子:
{{#if (itemSelected "SomeItem")}}
<div>This was selected</div>
{{/if}
我做了实验并证实它只是起作用。
不确定是否在Handlebars文档中提到它。我从handlebars-layouts的例子中学到了这个技巧。
这应该是更高的了。 – Aerowind 2015-09-08 17:08:29
是的,这是[subexpression](http://handlebarsjs.com/expressions.html#subexpressions)。它得到官方支持,所以这是最简单的方法。 – Pathoschild 2015-09-26 21:16:53
谢谢!那应该被标记为正确的答案。 – kokeksibir 2015-09-28 10:49:01
通过删除胡子和添加handlebars.js修复您的标记 – Rajat 2012-05-03 10:07:37