Craig Ward Craig Ward - 1 month ago 21
Twig Question

laravel csrf tokens with Twig

In Laravel the main app template has the following line

<script>window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token(),]); ?></script>


I'm using Twig for templates and need to change that line to work with Twig. However, I would have thought changing it to to

<script>window.Laravel = {{ data|json_encode(['csrfToken': csrf_token(),]) }}</script>
or
<script>window.Laravel = {{ data|json_encode(['csrfToken' => csrf_token(),]) }}</script>

would do the trick but it just errors. Whats the correct way to rewrite this?

Answer

Correct format should be:

<script>window.Laravel = {{ {'csrfToken': csrf_token()}|json_encode()|raw }}</script>

See for more info: http://twig.sensiolabs.org/doc/filters/json_encode.html