在Twig中输出数组

22

我尝试从数据库输出一个数组到屏幕上。 在我的实体中:

/**
 * @ORM\Column(type="array", nullable=true)
 */
private $category;

在我的twig模板中:

{% for category in user.profile.category %}
    {{ category }}
{% endfor %}

错误: 在...中将数组转换为字符串

我的错误出在哪里?

5个回答

31

因此,错误提示显示您正在尝试将数组(在category变量中)转换为字符串。您可以通过dump()文档)预览数组。在您的情况下:

{% for category in user.profile.category %}
    {{ dump(category) }}
{% endfor %}

请注意,dump()仅适用于调试。


24
你可以使用 join 将数组输出为一个连接的字符串。它的行为类似于 php 中的 implode()
示例:
{{ [1, 2, 3]|join }}
{# returns 123 #}

{{ [1, 2, 3]|join('|') }}
{# outputs 1|2|3 #}

{{ [1, 2, 3]|join(', ', ' and ') }}
{# outputs 1, 2 and 3 #}

请查看Twig join文档


1
这是文档的新链接:https://twig.symfony.com/doc/3.x/filters/join.html - Snow

7

TWIG不知道你想如何显示表格。

另外,你应该考虑将变量命名为$categories而不是$category,因为你的表格包含多个类别。

然后尝试这个:

{% for category in user.profile.categories %}
   {{ category }}
{% endfor %}

如果我的回答没有帮助到你,请告诉我们你的数组结构是什么样子的(它是否有键或子数组,还是只是一个列表?)。

0

对于任何想要轻松输出关联数组的人:

(这里,数组是user.profile.category)

        <table>
            <tr>
                {% for key,value in user.profile.category[0] %}
                    <td>{{key|e }}</td>
                {% endfor %}
            </tr>

            {% for cat in user.profile.category %}
                <tr>
                    {% for cell in cat %}
                        <td>{{ cell|e }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </table>

0
在Opencart 4中,您需要添加以下代码:

$this->addExtension(new \Twig\Extension\DebugExtension());

public function __construct(LoaderInterface $loader, $options = []) system\storage\vendor\twig\twig\src\Environment.php

并启用以下代码:

'set debug' => true, // 初始化Twig环境

public function render(string $filename, array $data = [], string $code = ''): string { system\library\template\twig.php


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接