Convert the code in twig from PHP
Get the solution ↓↓↓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?
Answer
Solution:
The problem is that in your twig code, you've initialized the variablefontpre
with the string literalbody_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 thereplace
function altogether (as you can directly set it right.)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function format() on string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.