0

I have a twig template for some text field. Inside it I'm displaying the value like (it's single value field):

{% for item in items %}
  {{ item.content}}
{% endfor %}

And it's displaying value correctly, which means that inside that loop item.content contains correct value.

Now, field value actually contains tags, i.e. value is "tag1 tag2 tag 3". And I want to split that value by space sign. So I tried something like:

{% for item in items %}
  {% set tags = item.content|split(' ') %}
  {{ dump(tags) }}
  {{ item.content}}
{% endfor %}

And this split function should return list of elements 'tag1', 'tag2', 'tag3', according to documentation: https://twig.symfony.com/doc/2.x/filters/split.html

But instead, this dump call prints out null ?!?!

Why is that happening?

3

In a field.html.twig template {{ item.content }} is a render array. You can't use it in functions which expect a scalar like boolean, integer or string.

If you want to use field values in TWIG code better use the field object #items:

{% for item in element['#items'] %}
  {% set tags = item.value|split(' ') %}
  {{ dump(tags) }}
{% endfor %}

In a single value field you can access the value directly without a loop element['#items'].value.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.