我尝试从数据库输出一个数组到屏幕上。 在我的实体中:
/**
* @ORM\Column(type="array", nullable=true)
*/
private $category;
在我的twig模板中:
{% for category in user.profile.category %}
{{ category }}
{% endfor %}
错误: 在...中将数组转换为字符串
我的错误出在哪里?
我尝试从数据库输出一个数组到屏幕上。 在我的实体中:
/**
* @ORM\Column(type="array", nullable=true)
*/
private $category;
在我的twig模板中:
{% for category in user.profile.category %}
{{ category }}
{% endfor %}
错误: 在...中将数组转换为字符串
我的错误出在哪里?
因此,错误提示显示您正在尝试将数组(在category
变量中)转换为字符串。您可以通过dump()
(文档)预览数组。在您的情况下:
{% for category in user.profile.category %}
{{ dump(category) }}
{% endfor %}
请注意,dump()
仅适用于调试。
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文档。
TWIG不知道你想如何显示表格。
另外,你应该考虑将变量命名为$categories
而不是$category
,因为你的表格包含多个类别。
然后尝试这个:
{% for category in user.profile.categories %}
{{ category }}
{% endfor %}
对于任何想要轻松输出关联数组的人:
(这里,数组是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>
$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