简体   繁体   中英

How to use a twig-variable as a parameter for a javascript function?

I have the variable kalender in Twig, which holds an object. I'm trying to use this variable as a parameter in a javascript function like this:

{% block script %}

    <script> kalenderGenerate({{ kalender }}); </script>

{% endblock %}

However doing so gives me the error

Uncaught SyntaxError: Unexpected token '&'

Upon investigation on that line it shows me this:

<script> kalenderGenerate([{&quot;id&quot;:56,&quot;datum&quot;:&quot;22.03.2021&quot;,&quot;tageszeit&quot;:&quot;Vormittag&quot;,&quot;dienste_termine_id&quot;:1},{&quot;id&quot;:57,&quot;datum&quot;:&quot;22.03.2021&quot;,&quot;tageszeit&quot;:&quot;Vormittag&quot;,&quot;dienste_termine_id&quot;:11},{&quot;id&quot;:58,&quot;datum&quot;:&quot;22.03.2021&quot;,&quot;tageszeit&quot;:&quot;Vormittag&quot;,&quot;dienste_termine_id&quot;:1}]); </script>

How can I actually pass this variable to be usable in JavaScript?

I tried it as <script> kalenderGenerate( {{ kalender|json_encode()|raw }} ); </script> <script> kalenderGenerate( {{ kalender|json_encode()|raw }} ); </script> which now passes my object as an array. This works as a workaround in my case, however if anyone has a better solution, that would be very appreciated.

Edit: Looks like the array doesn't entirely work after all. Any alternatives are greatly appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM