str_replace in Twig

PhpFilterStr ReplaceTwig

Php Problem Overview


I want to do a simple str_replace in my twig template. I'm new to twig and probably I need to add new filter or sth like that or to use existing. How can I do this? Where can I find list of filters available?

Php Solutions


Solution 1 - Php

Use this to replace | with - and replace , width .:

{{age|replace({'|': "-", "," : "."})}}

Example input 31|60, comes out as 31-60.

Solution 2 - Php

To replace a string which is stored in twig variables:

{% set twig_content_variable= 'Testing to replace content'%}
{% set replace_value_var= 'Testing' %}
{% set replace_with_value_var = 'Testing complete' %} 

{{ twig_content_variable|replace({ (replace_value_var): replace_with_value_var }) }}

Solution 3 - Php

Also, this could be useful for getting rid of (utf-8) language chars...

{{some_string|replace({'ć':'c','č':'c','š':'s','ž':'z','đ':'d','Ć':'C','Č':'C','Š':'S','Ž':'Z','Đ':'D'})}}

Solution 4 - Php

When we add a single quote inside a single quote then we face the error.

solution for that:-

{{description|replace({"\'": "&#039"})|raw }}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionumpirskyView Question on Stackoverflow
Solution 1 - PhpwebskyView Answer on Stackoverflow
Solution 2 - PhpM Khalid JunaidView Answer on Stackoverflow
Solution 3 - PhpDenis SolakovicView Answer on Stackoverflow
Solution 4 - PhpAshView Answer on Stackoverflow