Siv*_*mar 7 jquery handlebars.js
车把 JS 有没有办法检查一个值的长度?像这样的东西:
{{#if value.length > 20}
..do something
{{else}}
..do something
{{/if}}
Run Code Online (Sandbox Code Playgroud)
Moh*_*mar 14
创建如下所示的Handlebars助手: -
Handlebars.registerHelper('checklength', function (v1, v2, options) {
'use strict';
if (v1.length>v2) {
return options.fn(this);
}
return options.inverse(this);
});
Run Code Online (Sandbox Code Playgroud)
并使用它像: -
{{#checklength jobTitle 20}} //jobtitle is property and 20 is length
<p>Up to 20</p>
{{else}}
<p>Less then 20</p>
{{/checklength}}
Run Code Online (Sandbox Code Playgroud)
But*_*uts 12
只是想改进接受的答案,这是非常正确和有帮助的,但......
而不是专门针对某些事情长度,你可以使它大于条件,并在其他更大的情况下使用它.
Handlebars.registerHelper('greaterThan', function (v1, v2, options) {
'use strict';
if (v1>v2) {
return options.fn(this);
}
return options.inverse(this);
});
Run Code Online (Sandbox Code Playgroud)
并使用这样的:
{{#greaterThan jobTitle.length 20}}
<p>Up to 20</p>
{{else}}
<p>Less then 20</p>
{{/greaterThan}}
Run Code Online (Sandbox Code Playgroud)
这样你可以比较很多不同的东西,而不仅仅是长度.
您还可以更进一步,让我们考虑一下我们可能想要检查某些东西是否小于其他东西或等于其他东西.
Handlebars.registerHelper('compare', function (v1, operator, v2, options) {
'use strict';
var operators = {
'==': v1 == v2 ? true : false,
'===': v1 === v2 ? true : false,
'!=': v1 != v2 ? true : false,
'!==': v1 !== v2 ? true : false,
'>': v1 > v2 ? true : false,
'>=': v1 >= v2 ? true : false,
'<': v1 < v2 ? true : false,
'<=': v1 <= v2 ? true : false,
'||': v1 || v2 ? true : false,
'&&': v1 && v2 ? true : false
}
if (operators.hasOwnProperty(operator)) {
if (operators[operator]) {
return options.fn(this);
}
return options.inverse(this);
}
return console.error('Error: Expression "' + operator + '" not found');
});
Run Code Online (Sandbox Code Playgroud)
使用上面的帮助器,我们可以比较各种可能性.
{{#compare jobTitle.length '>' 20}}
{{#compare jobTitle.length '<=' 100}}
<p>Greater than 20 and less than or equal 100</p>
{{else}}
<p>Greater than 100</p>
{{/compare}}
{{else}}
<p>Less than or equal to 20</p>
{{/compare}}
Run Code Online (Sandbox Code Playgroud)
如果您发现很难理解这个助手是如何工作的,请阅读Todd Mottos关于使用对象文字而不是switch语句的文章.
Dan*_*scu 12
不清楚你value是什么,字符串还是数组?
如果是数组,则不需要助手!您可以检查该项目是否length存在:
{{#if items.[20]}}
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例,用于在用户有一个项目与多个项目时显示不同的消息:
{{#if items.[1]}}
You have the following items:
{{#each items}}
* {{this}}
{{/each}}
{{else}}
You have one item: {{items.[0]}}
{{/if}}
Run Code Online (Sandbox Code Playgroud)
在http://tryhandlebarsjs.com/尝试使用示例数据,例如
{
items: ["foo", "bar"]
}
Run Code Online (Sandbox Code Playgroud)
不需要帮助程序对于在邮件传递服务(Sparkpost、Sendgrid、Mandrill 等)的动态模板中使用 Handlebars 非常重要,这些模板不允许定义帮助程序(尽管 Sparkpost 的语法比 Sendgrid 丰富得多)。