Twig中的输出数组

now*_*iko 11 arrays longtext symfony doctrine-orm twig

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

/**
 * @ORM\Column(type="array", nullable=true)
 */
private $category;
Run Code Online (Sandbox Code Playgroud)

在我的树枝模板中:

{% for category in user.profile.category %}
    {{ category }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

错误: Array to string conversion in ...

我的错误在哪里?

NHG*_*NHG 16

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

{% for category in user.profile.category %}
    {{ dump(category) }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

请注意,dump()应仅用于调试.


mil*_*sky 13

您可以使用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 #}
Run Code Online (Sandbox Code Playgroud)

请参阅twig join文档.


Bla*_*sad 6

TWIG不知道你想如何展示你的桌子.

顺便说一句,你应该考虑命名你的变量$categories而不是$category,因为你的表包含几个类别.

然后尝试这个:

{% for category in user.profile.categories %}
   {{ category }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

如果我的回答没有帮助,请告诉我们您的数组的结构(您的表中是否有任何键或子数组,或者它只是一个列表?)