user8302249 user8302249 - 1 month ago 9
Twig Question

Convert the code in twig from PHP

I have try to converted my templates to Twig code and I'm not sure from looking at the code how I would write the following examples out in Twig code. Can anyone point me in the right direction?

My following Php code.

<?php } if ($body_font != '' ) {
$fontpre = $body_font;
$font = str_replace("+", " ", $fontpre); ?>
body {font-family:<?php echo $font ?>;}
<?php } ?>


I have try something following in twig.

{% if body_font != '' %}
{% set fontpre = 'body_font' %}
{% set font = fontpre|replace("+", " ") %}
body {font-family:{{ font }}; }
{% endif %}


But, This doesn't work. can you please help. what do wrong here?

Answer Source

The replace filter is different from PHP function str_replace. It accepts a mapping where keys are strings that should be replaced by values:

{% set font = fontpre|replace({"+": " "}) %}