string Handlebarsjs 检查字符串是否等于值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34252817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handlebarsjs check if a string is equal to a value
提问by colmulhall
Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can't seem to find anything relevant to this in the Handlebars reference.
在 Handlebars 中是否可以在不注册帮助程序的情况下检查字符串是否等于另一个值?我似乎无法在 Handlebars 参考中找到与此相关的任何内容。
For example:
例如:
{{#if sampleString == "This is a string"}}
...do something
{{/if}}
回答by Mihail
It seems you can't do it "directly"
看来你不能“直接”做到
Try use helper, why not?
尝试使用助手,为什么不呢?
Register helper in your javascript code:
在您的 javascript 代码中注册助手:
Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});
Use in template:
在模板中使用:
{{#ifEquals sampleString "This is a string"}}
Your HTML here
{{/ifEquals}}
More details here: Logical operator in a handlebars.js {{#if}} conditional
此处有更多详细信息: handlebars.js {{#if}} 条件中的逻辑运算符
Update:Another way:
更新:另一种方式:
lets assume, your data is:
让我们假设,您的数据是:
var data = {
sampleString: 'This is a string'
};
Then (using jQuery):
然后(使用 jQuery):
$.extend(data, {isSampleString: function() {
return this.sampleString == 'This is a string';}
});
An use template:
一个使用模板:
{{#if isSampleString}}
Your HTML here
{{/if}}
回答by Pablo Varando
I would just use helpers like this:
我只会使用这样的助手:
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);
});
Then in your code:
然后在你的代码中:
{{#ifeq variable "string"}}
... do this ...
{{/ifeq}}
{{#ifnoteq variable "string"}}
... do this ...
{{/ifnoteq}}
回答by Kerhael
The previous answer with matchdoes not work for me, I get an error on the ifstatement (something like 'must have only one argument').
上一个带有match 的答案对我不起作用,我在if语句中出现错误(类似于“必须只有一个参数”)。
However, I just found the solution herewithout having to write any more helper:
{{#if (eq person "John")}} hello {{/if}}
回答by Jon
Just came to this post from a google search on how to check if a string equals another string.
刚刚从谷歌搜索到如何检查一个字符串是否等于另一个字符串的这篇文章。
I use HandlebarsJS in NodeJS server-side, but I also use the same template files on the front-end using the browser version of HandlebarsJS to parse it. This meant that if I wanted a custom helper, I'd have to define it in 2 separate places, or assign a function to the object in question - too much effort!!
我在NodeJS服务器端使用HandlebarsJS,但我也在前端使用相同的模板文件使用浏览器版本的HandlebarsJS来解析它。这意味着如果我想要一个自定义助手,我必须在 2 个不同的地方定义它,或者为有问题的对象分配一个函数 - 太费力了!!
What people forget is that certain objects have inherit functions that can be used in the moustache template. In the case of a string:
人们忘记的是某些对象具有可以在 mustache 模板中使用的继承函数。在字符串的情况下:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
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.
包含整个匹配结果和任何括号捕获的匹配结果的数组;如果没有匹配项,则为 null。
We can use this method to return either an array of matches, or null
if no matches were found. This is perfect, because looking at the HandlebarsJS documentation http://handlebarsjs.com/builtin_helpers.html
我们可以使用此方法返回匹配数组,或者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 帮助器有条件地渲染块。如果它的参数返回 false、undefined、null、""、0 或 [],Handlebars 将不会渲染块。
So...
所以...
{{#if your_string.match "what_youre_looking_for"}}
String found :)
{{else}}
No match found :(
{{/if}}
UPDATE:
更新:
After testing on all browsers, this doesn't work on Firefox. HandlebarsJS passes other arguments to a function call, meaning that when String.prototype.match is called, the second argument (i.e. the Regexp flags for the match function call as per above documentation) appears to be being passed. Firefox sees this as a deprecated use of String.prototype.match, and so breaks.
在所有浏览器上测试后,这在 Firefox 上不起作用。HandlebarsJS 将其他参数传递给函数调用,这意味着当调用 String.prototype.match 时,第二个参数(即上述文档中匹配函数调用的 Regexp 标志)似乎正在传递。Firefox 认为这是不推荐使用的 String.prototype.match,因此中断。
A workaround is to declare a new functional prototype for the String JS object, and use that instead:
一种解决方法是为 String JS object 声明一个新的功能原型,并使用它:
if(typeof String.includes !== 'function') {
String.prototype.includes = function(str) {
if(!(str instanceof RegExp))
str = new RegExp((str+'').escapeRegExp(),'g');
return str.test(this);
}
}
Ensure this JS code is included beforeyou run your Handlebars.compile() function, then in your template...
确保在运行 Handlebars.compile() 函数之前包含此 JS 代码,然后在模板中...
{{#your_string}}
{{#if (includes "what_youre_looking_for")}}
String found :)
{{else}}
No match found :(
{{/if}}
{{/your_string}}
回答by Vic Seedoubleyew
Use handlebars-helpers, which provides eq
helper
使用handlebars-helpers,它提供了eq
helper
回答by user11258971
Node.js add this in server.js
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);
回答by Ojus sangoi
You cannot directly compare the strings in handlebars and you have to use a helper. I tried the above solutions with my Koa app and couldn't register the helper. The below code worked for me and i think this should work for express apps as well. I hope this helps someone.
您不能直接比较车把中的字符串,您必须使用助手。我用我的 Koa 应用程序尝试了上述解决方案,但无法注册帮助程序。下面的代码对我有用,我认为这也适用于 express 应用程序。我希望这可以帮助别人。
Code in server.js
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
}
}));
Code in HBS file where fruit is the variable to be compared:
HBS 文件中的代码,其中水果是要比较的变量:
<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>
回答by Joel Kozikowski
In Handlebars, the parenthesis are used to invoke the first item listed as a function, using (optional) subsequent items as parameters. So, the syntax from Ember CAN be used without Ember, provided you can set the context yourself. For example:
在 Handlebars 中,括号用于调用作为函数列出的第一项,使用(可选)后续项作为参数。因此,Ember 的语法可以在没有 Ember 的情况下使用,前提是您可以自己设置上下文。例如:
context.eq = function(param1, param2) {
return param1 === param2;
}
context.notEq = function(param1, param2) {
return param1 !== param2;
}
Once you do that, you can use the standard {{#if}} and {{#unless}} block operations:
一旦你这样做了,你就可以使用标准的 {{#if}} 和 {{#unless}} 块操作:
{{#if (eq someVar "someValue") }}
Be careful of switching contexts with {{with}} or when using inline partials. You can lose track of your defined "eq" function. The guaranteed way to work, regardless of new contexts:
使用 {{with}} 或使用内联部分时要小心切换上下文。您可能会忘记定义的“eq”函数。有保证的工作方式,无论新环境如何:
{{#if (@root.eq someVar "someValue") }}
回答by Jeff Matthews
A common case for a simple, re-usable helper function is to cause a return of string1 if values are equal and string2 if they are not.
一个简单的、可重用的辅助函数的常见情况是,如果值相等则返回 string1,否则返回 string2。
Example:
例子:
Helper (let's call it "ifEqual" and send 4 parameters):
Helper(我们称之为“ifEqual”并发送 4 个参数):
helpers: {
ifEqual: function (obj, value, trueString, falseString) {
return ( (obj===value) ? trueString : falseString );
}
Template Use:
模板用途:
For this example, assume the template receives a "transaction" object with a "transactionType" property: { transactionType: "expense", description: "Copies" }
对于此示例,假设模板接收具有“transactionType”属性的“transaction”对象: { transactionType: "expense", description: "Copies" }
Let's say our template has a <select>
for the Transaction Type, with various <option>s
as shown. We want to use Handlebars to pre-select the option which coincides with the value of transactionType.
假设我们的模板有一个<select>
事务类型,<option>s
如图所示。我们要使用 Handlebars 来预先选择与 transactionType 的值一致的选项。
Our new {{ ifEqual }}
helper is used to insert "selected" for the <option>
with the matching value of "expense."
我们的新{{ ifEqual }}
助手用于为<option>
匹配值“费用”插入“选择” 。
<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>
回答by user2662680
Try:
尝试:
{{#is item.status "complete"}} ... {{/is}}
{{#is item.status "complete"}} ... {{/is}}