Macbernie Macbernie - 1 month ago 16
Twig Question

Array to string conversion, with split

I have a text like: 000325175
and I want to format it as: 000 325 175.

Nothing's easier (in theory) with the split filter, as:

{{ mynumber|split('', 3) }}


But I get a

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion")


However I can apply a slice filter without any problem.

{{ mynumber|slice(9, 14) }}


So I don't understand. Thanks for help

Answer

The split filter return an array (with the spitted values), you should only iterate over the result to display it as follow:

{% for partial in mynumber|split('', 3) %}
 {{ partial}} 
{% endfor %}

Here a working solutions

EDIT:

You can also use the join filter and concatenate the results as example:

{{ mynumber|split('', 3)|join(' ') }}