Kiksy
Kiksy

Reputation: 1292

Twig - Trying to split an array element

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?

Upvotes: 2

Views: 15210

Answers (2)

Particule42
Particule42

Reputation: 25

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.

Upvotes: 1

Dani Sancas
Dani Sancas

Reputation: 1375

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

Upvotes: 4

Related Questions