Output array in Twig

82,675

Solution 1

TWIG doesn't know how you want to display your table.

By the way, you should consider naming your variable $categories instead of $category, as you table contains several categories.

Then try this:

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

If my answer doesn't help, please give us the structure of your array (is there any keys or sub-arrays in you table or is it just a list?)

Solution 2

So, as error shows you are trying convert array (in category variable) to string. You can preview array by dump() (doc.). In your case:

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

Please notice that dump() should be use only for debugging.

Solution 3

You can use join to output an array as a concatenated string. It behaves like implode() in php.

Example:

{{ [1, 2, 3]|join }}
{# returns 123 #}

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

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

See the twig join documentation.

Share:
82,675
nowiko
Author by

nowiko

Updated on July 09, 2022

Comments

  • nowiko
    nowiko almost 2 years

    I trying to output an array from the database to the screen. In my entity:

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

    In my twig template:

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

    Error: Array to string conversion in ...

    Where is my mistake?

  • Snow
    Snow over 2 years
    Here the new link fot the doc : twig.symfony.com/doc/3.x/filters/join.html
  • milkovsky
    milkovsky over 2 years
    @Snow, thank you, I updated the link