Craig Ward Craig Ward - 9 months ago 109
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>
<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 Source

Correct format should be:

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

See for more info: