如果 twig 中为 null,则设置默认值

问题描述 投票:0回答:3

我正在树枝视图中循环我的结果..

{% for item in items %}
    <li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
 {% endfor %}

如果数据库中的用户 ID 为 NULL,我想设置默认值“用户未知”。

如:

{% if item.userId is null %}
--> 设置默认值

注意:我知道在这里使用了 if else ,但是由于我在许多宫殿中都有这个 fistName - lastName ,所以我想避免在每个部分使用 if else 。我想在所有地方设置默认值,以防 userId 为 null,而不是在每个地方重复代码。

我怎样才能做到这一点?

php symfony twig
3个回答
4
投票

编辑

您可以使用以下方式设置变量:

{% set name = item.userId is null ? 'User unknown' : item.userId.firstName ~ ' ' ~ item.userId.lastName %}

如果设置的意思是输出“用户未知”,一个简单的 if else 语句就可以解决问题

{% for item in items %}
    {% if item.userId is null %}
        <li>User unknown</li>
    {% else %}
        <li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
    {% endif %}
{% endfor %}

2
投票

在渲染输出的代码中设置默认值可能更容易,其中

items
被发送到 Twig。
array_merge
通常用于此目的 -
$item = array_merge($defaultItem, $item);
。在这里,$item 覆盖默认值设置。

在模板中,您还可以在各个字段上使用空合并运算符

??
{{ item.userId.firstName ?? 'unknown firstName' }}


2
投票

也许有点晚了,但 Twig 似乎有一个默认值的过滤器:

https://twig.symfony.com/doc/2.x/filters/default.html

© www.soinside.com 2019 - 2024. All rights reserved.