php 字符串比较运算符如何在 Twig 中工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16199284/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:42:37  来源:igfitidea点击:

How do string comparison operators work in Twig?

phptwig

提问by Scottymeuk

How is this possible? It seems to be a very very odd issue (unless I'm missing something very simple):

这怎么可能?这似乎是一个非常非常奇怪的问题(除非我遗漏了一些非常简单的东西):

Code:

代码:

{{ dump(nav) }}
{% if nav == "top" %}
    <div class="well">This would be the nav</div>
{% endif %}

Output:

输出:

boolean true
<div class="well">This would be the nav</div>

Screenshot

截屏

Basically, it is outputting if true, but it's not meant to be checking for true.

基本上,如果为真则输出,但并不意味着检查是否为真。

回答by Alain Tiemblo

This is easily reproductible :

这很容易重现:

{% set nav = true %}
{% if nav == "top" %}
ok
{% endif %}

Displays ok.

显示ok

According to the documentation:

根据文档

Twig allows expressions everywhere. These work very similarto regular PHP and even if you're not working with PHP you should feel comfortable with it.

Twig 允许在任何地方使用表达式。它们的工作方式常规 PHP非常相似,即使您不使用 PHP,您也应该对它感到满意。

And if you test in pure PHP the following expression :

如果您在纯 PHP 中测试以下表达式:

$var = true;
if ($var == "top") {
  echo 'ok';
}

It will also display ok.

它也会显示正常。

The point is : you should not compare variables of different types. Here, you compare a bool with a string : if your string is not empty or if it does not contains only zeros, it will evaluate to true.

关键是:你不应该比较不同类型的变量。在这里,您将 bool 与字符串进行比较:如果您的字符串不为空或不只包含零,则它将评估为真。

You can also have a look to the PHP manualto see how comparison are made with different types.

您还可以查看PHP 手册以了解如何与不同类型进行比较。

Edit

编辑

You can use the sameastest to make strict comparisions, and avoid type juggling matters.

您可以使用相同的测试进行严格的比较,并避免类型杂耍问题。