How to replace string in twig?

Member

by odessa , in category: PHP , 2 years ago

How to replace string in twig?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@odessa You can use filter replace to replace string in Twig, here is code as example how to replace "ipsum" to "test":


1
2
{{ "Lorem ipsum dolor sit amet."|replace({"ipsum": "test"}) }}
{# Output: Lorem test dolor sit amet. #}


Member

by freddy , a year ago

@odessa 

In Twig, you can replace a string using the replace filter. The replace filter takes two arguments: the first argument is the string to search for, and the second argument is the string to replace it with.


Here's an example:

1
2
{% set myString = "Hello World" %}
{{ myString|replace({'Hello': 'Hi'}) }}


In this example, the replace filter is used to replace the string "Hello" with "Hi" in the myString variable. The output of this code would be "Hi World".


You can also use the replace filter to replace multiple strings at once. Here's an example:

1
2
{% set myString = "Hello World" %}
{{ myString|replace({'Hello': 'Hi', 'World': 'Universe'}) }}


In this example, the replace filter is used to replace both "Hello" with "Hi" and "World" with "Universe" in the myString variable. The output of this code would be "Hi Universe".