Twig - Trying to split an array element

12,278

Solution 1

From the official doc:

The split filter splits a string by the given delimiter and returns a list of strings:

{{ "one,two,three"|split(',') }}
{# returns ['one', 'two', 'three'] #}

So, taking your code, you could do something like:

{% for result in resultset %}
    {{ set myArray = result.postcode|split(' ') }}
    {{ myArray[0] }} {# Will output "AB1" #}
{% endfor %}

Source: TWIG Split filter

Solution 2

It's an old question but the real problem is that you asked Twig to display the result of your split using a {{...}} block. You should use the {%...%} block and set tag, as explained in the documentation.

If you only want to display some part, you can use either split with [first][2] filter or slice.

Share:
12,278
Kiksy
Author by

Kiksy

Updated on June 05, 2022

Comments

  • Kiksy
    Kiksy almost 2 years

    Im looping over an array of objects, and then trying to split one of the elements, in this case I want to split the postcode on the space. Ie. 'AB1 1AB' should just be 'AB1' .

    {% for result in resultset %}
                {{ result.postcode|split(' ') }}
        {% endfor %}
    

    Throws me an 'array to string error'

    Trying just:

    {{ result.postcode[0] }}
    

    Throws me a 'impossible to access key [0] on a string varaible' error.

    and just doing:

    {{ result.postcode }}   
    

    gives me no error, with the postcode displayed as 'AB1 1AB'

    Why does Twig think the string is an array when I try to split it?