user8302249
user8302249

Reputation: 91

Convert the code in twig from PHP

I have tried to convert my templates from plain PHP 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 tried 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 I do wrong here?

Upvotes: 2

Views: 276

Answers (2)

Timurib
Timurib

Reputation: 2743

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({"+": " "}) %}

Upvotes: 2

giorgio
giorgio

Reputation: 10212

The problem is that in your twig code, you've initialized the variable fontpre with the string literal body_font. While in your php code, $body_font is a variable as well.

It is actually quite useless to set it again, you could use that variable directly in your php code (eg. $font = str_replace("+", " ", $body_font); ?>), but besides that; make sure that this particular variable is available in your twig code as well, or use a string literal referencing to a proper font family name. Although in that case you could skip the replace function altogether (as you can directly set it right.)

Upvotes: 0

Related Questions