Handlebarsjs 检查一个字符串是否等于一个值
Handlebarsjs check if a string is equal to a value
是否可以在 Handlebars 中检查字符串是否等于另一个值而无需注册助手?我似乎无法在 Handlebars 参考中找到与此相关的任何内容。
例如:
{{#if sampleString == "This is a string"}}
...do something
{{/if}}
看来你做不到"directly"
尝试使用助手,为什么不呢?
在您的 javascript 代码中注册助手:
Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});
在模板中使用:
{{#ifEquals sampleString "This is a string"}}
Your HTML here
{{/ifEquals}}
这里有更多详细信息:
Logical operator in a handlebars.js {{#if}} conditional
更新:
另一种方式:
假设您的数据是:
var data = {
sampleString: 'This is a string'
};
然后(使用jQuery):
$.extend(data, {isSampleString: function() {
return this.sampleString == 'This is a string';}
});
一个使用模板:
{{#if isSampleString}}
Your HTML here
{{/if}}
刚从google搜索如何检查一个字符串是否等于另一个字符串得到这个post。
我在 NodeJS 服务器端使用 HandlebarsJS,但我也在前端使用相同的模板文件,使用浏览器版本的 HandlebarsJS 来解析它。这意味着如果我想要一个自定义助手,我必须在 2 个不同的地方定义它,或者为相关对象分配一个函数 - 太费力了!!
人们忘记的是,某些对象具有可以在小胡子模板中使用的继承函数。如果是字符串:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.
我们可以使用此方法 return 匹配数组,或者 null
如果未找到匹配项。这是完美的,因为查看 HandlebarsJS 文档 http://handlebarsjs.com/builtin_helpers.html
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
所以...
{{#if your_string.match "what_youre_looking_for"}}
String found :)
{{else}}
No match found :(
{{/if}}
更新:
在所有浏览器上测试后,这在 Firefox 上不起作用。 HandlebarsJS 将其他参数传递给函数调用,这意味着当调用 String.prototype.match 时,第二个参数(即根据上述文档的匹配函数调用的 Regexp 标志)似乎正在传递。 Firefox 认为这是对 String.prototype.match 的弃用,因此中断。
解决方法是为 String JS 对象声明一个新的函数原型,然后改用它:
if(typeof String.includes !== 'function') {
String.prototype.includes = function(str) {
if(!(str instanceof RegExp))
str = new RegExp((str+'').escapeRegExp(),'g');
return str.test(this);
}
}
确保在你运行你的Handlebars.compile()函数之前包含这个JS代码,然后在你的模板中...
{{#your_string}}
{{#if (includes "what_youre_looking_for")}}
String found :)
{{else}}
No match found :(
{{/if}}
{{/your_string}}
之前使用 match 的答案对我不起作用,我在 if 语句中遇到错误(类似于 'must have only one argument').
然而,我只是找到了解决方案 here 而无需再编写任何帮助程序:
{{#if (eq person "John")}} hello {{/if}}
Mandrill 邮件服务支持 Handlebars,这里可以使用 "backticks" 计算 #if 块中的逻辑表达式:
{{#if `operating_system == "OS X"`}}
<p>Click here for instructions to install on a Mac</p>
{{elseif `operating_system == "Windows"`}}
<p>Click here for instructions to install on a PC</p>
{{/if}}
我不知道这在一般情况下是否可行,但您应该尝试一下。
这对我来说可以。
Handlebars 有一个名为 'equal' 的条件运算符,它有两个参数:
1.The变量
2.what 你检查变量是否包含。
例如,检查'status'是否包含'Full Time':
{{#equal status "Full Time"}} //status is the variable and Full Time is the value your checking for.
code to be executed
{{else}}
code to be executed
{{/equal}}
一个简单的、可重复使用的辅助函数的常见情况是,如果值相等则 return 为 string1,否则为 string2。
示例:
Helper(我们称它为"ifEqual"并发送4个参数):
helpers: {
ifEqual: function (obj, value, trueString, falseString) {
return ( (obj===value) ? trueString : falseString );
}
模板使用:
对于这个例子,假设模板接收到一个 "transaction" 对象和 "transactionType" 属性:{ transactionType: "expense", description: "Copies" }
假设我们的模板有一个 <select>
交易类型,如图所示有各种 <option>s
。我们想使用 Handlebars 预先 select 与 transactionType 的值一致的选项。
我们新的 {{ ifEqual }}
帮助程序用于为匹配值为 "expense."
的 <option>
插入 "selected"
<select required id="selTransactionType" name="selTransactionType" class="form-control" onchange='transactionTypeChanged()'>
<option value='hourly' {{ ifEqual transaction.transactionType "hourly" "selected" "" }} >Hourly fee</option>
<option value='flat' {{ ifEqual transaction.transactionType "flat" "selected" "" }} >Flat fee</option>
<option value='expense' {{ ifEqual transaction.transactionType "expense" "selected" "" }} >Expense</option>
<option value='payment' {{ ifEqual transaction.transactionType "payment" "selected" "" }} >Payment</option>
<option value='credit' {{ ifEqual transaction.transactionType "credit" "selected" "" }} >Credit</option>
<option value='debit' {{ ifEqual transaction.transactionType "debit" "selected" "" }} >Debit</option>
</select>
我会像这样使用助手:
Handlebars.registerHelper('ifeq', function (a, b, options) {
if (a == b) { return options.fn(this); }
return options.inverse(this);
});
Handlebars.registerHelper('ifnoteq', function (a, b, options) {
if (a != b) { return options.fn(this); }
return options.inverse(this);
});
然后在你的代码中:
{{#ifeq variable "string"}}
... do this ...
{{/ifeq}}
{{#ifnoteq variable "string"}}
... do this ...
{{/ifnoteq}}
您不能直接比较车把中的字符串,必须使用助手。我用我的 Koa 应用程序尝试了上述解决方案,但无法注册助手。下面的代码对我有用,我认为这也适用于 express 应用程序。我希望这对某人有所帮助。
server.js中的代码
var handlebars = require('koa-handlebars');
const isEqualHelperHandlerbar = function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
}
app.use(handlebars({
viewsDir: './app/views',
layoutsDir: './app/views/layouts',
defaultLayout: 'main',
helpers : {
if_equal : isEqualHelperHandlerbar
}
}));
HBS 文件中的代码,其中 fruit 是要比较的变量:
<select id={{fruit}}>
<option >Choose...</option>
<option value="apple" {{#if_equal fruit "apple"}} selected {{/if_equal}}>Apple</option>
<option value="mango" {{#if_equal fruit "mango"}} selected {{/if_equal}} >Mango</option>
</select>
在 Handlebars 中,括号用于调用作为函数列出的第一项,使用(可选的)后续项作为参数。因此,如果您可以自己设置上下文,则可以在没有 Ember 的情况下使用 Ember 中的语法。例如:
context.eq = function(param1, param2) {
return param1 === param2;
}
context.notEq = function(param1, param2) {
return param1 !== param2;
}
完成后,您可以使用标准的 {{#if}} 和 {{#unless}} 块操作:
{{#if (eq someVar "someValue") }}
使用 {{with}} 或使用内联部分时要小心切换上下文。您可能会忘记定义的 "eq" 函数。无论新环境如何,保证的工作方式:
{{#if (@root.eq someVar "someValue") }}
Node.js 在 server.js
中添加这个
const isEqual = function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
}
var hbs = require('hbs');
hbs.registerHelper('if_eq', isEqual);
使用 handlebars-helpers,它提供 eq
帮助程序
尝试:
{{#是item.status"complete"}}
...
{{/是}}
我和 OP 遇到了同样的困难,所以决定将电话转租给 Javascript,而不是试图让 Handlebars 屈服于我的意愿...
Javascript 函数(在全局范围内)-
function jsIfElse(compare1, compare2, trueResponse, falseResponse) {
document.write((compare1 == compare2) ? trueResponse : falseResponse);
}
车把片段 -
<select multiple id="batter_player_team">
{{#each teamNamesForFilter}}
<option value="{{this.id}}"> <script>jsIfElse('{{this.is_active}}','Y','{{this.name}} *', '{{this.name}}');</script>
</option>
{{/each}}
</select>
对于不需要依赖项的单行解决方案,您可以使用:
Handlebars.registerHelper('eq', (a, b) => a == b)
然后像其他例子一样使用它作为嵌套调用:
{{#if (eq sampleString "This is a string"}}
...do something
{{/if}}
有很多答案,但如果有人遇到与我相同的错误,我会展示对我有用的答案(基本上会向我发送 options.fn 和 options.reverse 无效的错误)所以我决定使用 sub-expression 帮助程序寻求一个简单的解决方案并且它有效(未考虑因为我尝试了所有之前的解决方案,得到了相同的错误)
简而言之,我只是简单地比较两个参数并返回您想要的值,就像这样(使用助手)
在你的 server.js || app.js
Handlebars.registerHelper('functionName', function (value, value2) {
if(value == value2) {
return this;
}
});
在这种情况下,我不给出 else 条件,但如果你愿意,你可以这样做,这是 hbs 文件应该如何去
{{#if (functionName value value2)}}
在我的例子中,我在 value 中放入了我的数据库的值 (MongoDB),在 value2 中我用来比较一个字符串,所以我认为你可以比较任何类型的值,如果你正在迭代在每个确保你把 if 条件放在里面
最后但同样重要的是确保你的代码中有 const Handlebars = require('handlebars');
否则会向你发送错误,希望对某人有所帮助
您可以阅读 sub-expressions here
是否可以在 Handlebars 中检查字符串是否等于另一个值而无需注册助手?我似乎无法在 Handlebars 参考中找到与此相关的任何内容。
例如:
{{#if sampleString == "This is a string"}}
...do something
{{/if}}
看来你做不到"directly"
尝试使用助手,为什么不呢?
在您的 javascript 代码中注册助手:
Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});
在模板中使用:
{{#ifEquals sampleString "This is a string"}}
Your HTML here
{{/ifEquals}}
这里有更多详细信息: Logical operator in a handlebars.js {{#if}} conditional
更新: 另一种方式:
假设您的数据是:
var data = {
sampleString: 'This is a string'
};
然后(使用jQuery):
$.extend(data, {isSampleString: function() {
return this.sampleString == 'This is a string';}
});
一个使用模板:
{{#if isSampleString}}
Your HTML here
{{/if}}
刚从google搜索如何检查一个字符串是否等于另一个字符串得到这个post。
我在 NodeJS 服务器端使用 HandlebarsJS,但我也在前端使用相同的模板文件,使用浏览器版本的 HandlebarsJS 来解析它。这意味着如果我想要一个自定义助手,我必须在 2 个不同的地方定义它,或者为相关对象分配一个函数 - 太费力了!!
人们忘记的是,某些对象具有可以在小胡子模板中使用的继承函数。如果是字符串:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.
我们可以使用此方法 return 匹配数组,或者 null
如果未找到匹配项。这是完美的,因为查看 HandlebarsJS 文档 http://handlebarsjs.com/builtin_helpers.html
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
所以...
{{#if your_string.match "what_youre_looking_for"}}
String found :)
{{else}}
No match found :(
{{/if}}
更新:
在所有浏览器上测试后,这在 Firefox 上不起作用。 HandlebarsJS 将其他参数传递给函数调用,这意味着当调用 String.prototype.match 时,第二个参数(即根据上述文档的匹配函数调用的 Regexp 标志)似乎正在传递。 Firefox 认为这是对 String.prototype.match 的弃用,因此中断。
解决方法是为 String JS 对象声明一个新的函数原型,然后改用它:
if(typeof String.includes !== 'function') {
String.prototype.includes = function(str) {
if(!(str instanceof RegExp))
str = new RegExp((str+'').escapeRegExp(),'g');
return str.test(this);
}
}
确保在你运行你的Handlebars.compile()函数之前包含这个JS代码,然后在你的模板中...
{{#your_string}}
{{#if (includes "what_youre_looking_for")}}
String found :)
{{else}}
No match found :(
{{/if}}
{{/your_string}}
之前使用 match 的答案对我不起作用,我在 if 语句中遇到错误(类似于 'must have only one argument').
然而,我只是找到了解决方案 here 而无需再编写任何帮助程序:
{{#if (eq person "John")}} hello {{/if}}
Mandrill 邮件服务支持 Handlebars,这里可以使用 "backticks" 计算 #if 块中的逻辑表达式:
{{#if `operating_system == "OS X"`}}
<p>Click here for instructions to install on a Mac</p>
{{elseif `operating_system == "Windows"`}}
<p>Click here for instructions to install on a PC</p>
{{/if}}
我不知道这在一般情况下是否可行,但您应该尝试一下。 这对我来说可以。
Handlebars 有一个名为 'equal' 的条件运算符,它有两个参数:
1.The变量
2.what 你检查变量是否包含。
例如,检查'status'是否包含'Full Time':
{{#equal status "Full Time"}} //status is the variable and Full Time is the value your checking for.
code to be executed
{{else}}
code to be executed
{{/equal}}
一个简单的、可重复使用的辅助函数的常见情况是,如果值相等则 return 为 string1,否则为 string2。
示例:
Helper(我们称它为"ifEqual"并发送4个参数):
helpers: {
ifEqual: function (obj, value, trueString, falseString) {
return ( (obj===value) ? trueString : falseString );
}
模板使用:
对于这个例子,假设模板接收到一个 "transaction" 对象和 "transactionType" 属性:{ transactionType: "expense", description: "Copies" }
假设我们的模板有一个 <select>
交易类型,如图所示有各种 <option>s
。我们想使用 Handlebars 预先 select 与 transactionType 的值一致的选项。
我们新的 {{ ifEqual }}
帮助程序用于为匹配值为 "expense."
<option>
插入 "selected"
<select required id="selTransactionType" name="selTransactionType" class="form-control" onchange='transactionTypeChanged()'>
<option value='hourly' {{ ifEqual transaction.transactionType "hourly" "selected" "" }} >Hourly fee</option>
<option value='flat' {{ ifEqual transaction.transactionType "flat" "selected" "" }} >Flat fee</option>
<option value='expense' {{ ifEqual transaction.transactionType "expense" "selected" "" }} >Expense</option>
<option value='payment' {{ ifEqual transaction.transactionType "payment" "selected" "" }} >Payment</option>
<option value='credit' {{ ifEqual transaction.transactionType "credit" "selected" "" }} >Credit</option>
<option value='debit' {{ ifEqual transaction.transactionType "debit" "selected" "" }} >Debit</option>
</select>
我会像这样使用助手:
Handlebars.registerHelper('ifeq', function (a, b, options) {
if (a == b) { return options.fn(this); }
return options.inverse(this);
});
Handlebars.registerHelper('ifnoteq', function (a, b, options) {
if (a != b) { return options.fn(this); }
return options.inverse(this);
});
然后在你的代码中:
{{#ifeq variable "string"}}
... do this ...
{{/ifeq}}
{{#ifnoteq variable "string"}}
... do this ...
{{/ifnoteq}}
您不能直接比较车把中的字符串,必须使用助手。我用我的 Koa 应用程序尝试了上述解决方案,但无法注册助手。下面的代码对我有用,我认为这也适用于 express 应用程序。我希望这对某人有所帮助。
server.js中的代码
var handlebars = require('koa-handlebars');
const isEqualHelperHandlerbar = function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
}
app.use(handlebars({
viewsDir: './app/views',
layoutsDir: './app/views/layouts',
defaultLayout: 'main',
helpers : {
if_equal : isEqualHelperHandlerbar
}
}));
HBS 文件中的代码,其中 fruit 是要比较的变量:
<select id={{fruit}}>
<option >Choose...</option>
<option value="apple" {{#if_equal fruit "apple"}} selected {{/if_equal}}>Apple</option>
<option value="mango" {{#if_equal fruit "mango"}} selected {{/if_equal}} >Mango</option>
</select>
在 Handlebars 中,括号用于调用作为函数列出的第一项,使用(可选的)后续项作为参数。因此,如果您可以自己设置上下文,则可以在没有 Ember 的情况下使用 Ember 中的语法。例如:
context.eq = function(param1, param2) {
return param1 === param2;
}
context.notEq = function(param1, param2) {
return param1 !== param2;
}
完成后,您可以使用标准的 {{#if}} 和 {{#unless}} 块操作:
{{#if (eq someVar "someValue") }}
使用 {{with}} 或使用内联部分时要小心切换上下文。您可能会忘记定义的 "eq" 函数。无论新环境如何,保证的工作方式:
{{#if (@root.eq someVar "someValue") }}
Node.js 在 server.js
中添加这个const isEqual = function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
}
var hbs = require('hbs');
hbs.registerHelper('if_eq', isEqual);
使用 handlebars-helpers,它提供 eq
帮助程序
尝试:
{{#是item.status"complete"}} ... {{/是}}
我和 OP 遇到了同样的困难,所以决定将电话转租给 Javascript,而不是试图让 Handlebars 屈服于我的意愿...
Javascript 函数(在全局范围内)-
function jsIfElse(compare1, compare2, trueResponse, falseResponse) {
document.write((compare1 == compare2) ? trueResponse : falseResponse);
}
车把片段 -
<select multiple id="batter_player_team">
{{#each teamNamesForFilter}}
<option value="{{this.id}}"> <script>jsIfElse('{{this.is_active}}','Y','{{this.name}} *', '{{this.name}}');</script>
</option>
{{/each}}
</select>
对于不需要依赖项的单行解决方案,您可以使用:
Handlebars.registerHelper('eq', (a, b) => a == b)
然后像其他例子一样使用它作为嵌套调用:
{{#if (eq sampleString "This is a string"}}
...do something
{{/if}}
有很多答案,但如果有人遇到与我相同的错误,我会展示对我有用的答案(基本上会向我发送 options.fn 和 options.reverse 无效的错误)所以我决定使用 sub-expression 帮助程序寻求一个简单的解决方案并且它有效(未考虑因为我尝试了所有之前的解决方案,得到了相同的错误)
简而言之,我只是简单地比较两个参数并返回您想要的值,就像这样(使用助手)
在你的 server.js || app.js
Handlebars.registerHelper('functionName', function (value, value2) {
if(value == value2) {
return this;
}
});
在这种情况下,我不给出 else 条件,但如果你愿意,你可以这样做,这是 hbs 文件应该如何去
{{#if (functionName value value2)}}
在我的例子中,我在 value 中放入了我的数据库的值 (MongoDB),在 value2 中我用来比较一个字符串,所以我认为你可以比较任何类型的值,如果你正在迭代在每个确保你把 if 条件放在里面
最后但同样重要的是确保你的代码中有 const Handlebars = require('handlebars');
否则会向你发送错误,希望对某人有所帮助
您可以阅读 sub-expressions here