Score:3

How can I replace a string in a text?

zw flag

With {{ content.field_myfield.0 }}, I get a text. When I use {{ content.field_myfield.0|replace({"foo" : "bar"}) }}, nothing is rendered and no errors are reported.

I also tried replacing content.field_myfield.0 with content.field_myfield.value or `content.field_myfield.0.value, but I still get an empty string.

How can I replace a string?

Thanks

Score:7
in flag

content.field_some_field is a render array, but the replace filter operates on strings. You need to render your field before calling replace.

For example:

{{ content.field_some_field|render|replace({"hello": "goodbye"}) }}
Score:6
cn flag

If this is a formatted text field you can replace the source text before it is rendered. This has the advantage that HTML tags are preserved:

{% set field_item = content.field_myfield.0  %}
{% set text_replaced = field_item['#text']|replace({'foo': 'bar'}) %}
{{ field_item|merge({'#text': text_replaced}) }}

If you are not sure about the field type check the render array {{ dump(field_item) }}.

You can flatten the render array before replacing, as @sonfd suggested, if the replaced text doesn't contain HTML tags.

In general there are better ways to replace texts. Implement a text filter or a pre_render/post_render callback. See for example https://www.drupal.org/forum/support/module-development-and-code-questions/2020-01-28/creating-a-custom-text-filter or How to alter page content?

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.