How to render CSRF input in twig?

前端 未结 5 1622
野性不改
野性不改 2021-02-02 06:39

I know there\'s the usual way to render CSRF token hidden input with form_rest, but is there a way to render just CSRF input itself? I\'ve overridd

5条回答
  •  情深已故
    2021-02-02 06:52

    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.

     
    // 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

提交回复
热议问题