How to render CSRF input in twig?

you can do it with {{ form_widget(formView._token) }}


If you have formView object, you can render it using Twig function:

{{ form_widget(formView._token) }} 

If you haven't - you can render token without using form object directly:

<input type="hidden" name="token" value="{{ csrf_token('some-name') }}">

Works in Symfony 2.x and 3.x

To validate the token you can use the following code in your controller (Symfony 3.x):

$submittedToken = $request->request->get('token');

if ($this->isCsrfTokenValid('some-name', $submittedToken)) {
    // ... do something,
}

Or you can just simply use this :

{{ form_row(form._token) }}

This will automatically generate the proper hidden HTML elements, ie the proper HTML structure and field names, according to the type of form you're using.


I needed to render the csrf input inside Twig so that I could use it for Delete operations. Using {{ csrf_token('authenticate') }} as per @YuryPliashkou's answer gives me the incorrect token (one which is only valid for logins!)

What worked for me was this {{ csrf_token('form') }} which gives me the correct csrf token which I would then pass to my controller via ajax.

<span id="csrf_token" data-token="{{ csrf_token('form') }}"></span> 
// my ajax call
$.ajax({
    url: localhost/admin/product/4545,   // 4545->id of the item to be deleted
    type: 'POST',
    data: {
        "_method": "DELETE",
        "form[_token]": $("#csrf_token").data("token")   // passed csrf token here
    },
    success: function(result) {
        // Do something 
   }
});

Verified its working on Symfony 3.x.

Reference