programmer java
programmer java

Reputation: 49

Convert PHP to Twig

How can I convert this instruction :

<script>
<?php
 echo "sectionsPreview=".json_encode($this->groups).";\n";
 echo "typographyFonts=".json_encode($this->fontsDropdown).";\n";
?>
</script>

to Twig?

I did this:

{{ ((sectionsPreview'~groups|json_encode|raw) }}

Upvotes: 1

Views: 209

Answers (2)

isom
isom

Reputation: 304

You can make this if you want that your output text

{{ 'sectionsPreview='~groups|json_encode() }}

Upvotes: 0

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

In twig you can set js variables as

<script>

    var sectionsPreview = JSON.parse('{{ groups|json_encode() }}');
    var typographyFonts= JSON.parse('{{ fontsDropdown|json_encode() }}');

</script>

you may need JSON.parse to parse your string as json object

json_encode

Upvotes: 2

Related Questions