php twig if,if · Twig 中文文档 · 看云

#``if``

The ``if`` statement in Twig is comparable with the if statements of PHP.

In the simplest form you can use it to test if an expression evaluates to

``true``:

.. code-block:: jinja

{% if online == false %}

Our website is in maintenance mode. Please, come back later.

{% endif %}

You can also test if an array is not empty:

.. code-block:: jinja

{% if users %}

{% for user in users %}

{{ user.username|e }}

{% endfor %}

{% endif %}

.. note::

If you want to test if the variable is defined, use ``if users is

defined`` instead.

You can also use ``not`` to check for values that evaluate to ``false``:

.. code-block:: jinja

{% if not user.subscribed %}

You are not subscribed to our mailing list.

{% endif %}

For multiple conditions, ``and`` and ``or`` can be used:

.. code-block:: jinja

{% if temperature > 18 and temperature < 27 %}

It's a nice day for a walk in the park.

{% endif %}

For multiple branches ``elseif`` and ``else`` can be used like in PHP. You can

use more complex ``expressions`` there too:

.. code-block:: jinja

{% if kenny.sick %}

Kenny is sick.

{% elseif kenny.dead %}

You killed Kenny! You bastard!!!

{% else %}

Kenny looks okay --- so far

{% endif %}

.. note::

The rules to determine if an expression is ``true`` or ``false`` are the

same as in PHP; here are the edge cases rules:

====================== ====================

Value Boolean evaluation

====================== ====================

empty string false

numeric zero false

whitespace-only string true

empty array false

null false

non-empty array true

object true

====================== ====================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值