How do I access the CSRF token in a Phoenix template?

I want to write myself a little javascript helper function in a template. All it is going to do is post “hello world” back to my server. But I need the CSRF token. How can I access it in my template?

I don’t know which controller will render my template – this is in fact a partial that is included in the header of many templates and would end up being rendered on any page.

I can see get_csrf_token discussed in the docs for Phoenix controllers (Phoenix.Controller — Phoenix v1.6.2), but if I try to access this function from my template I get an error about an undefined function.

Ok, I guess that was a stupid question. But maybe it will help someone else down the line.

This doesn’t work:

    <%= get_csrf_token() %>

But this does work:

    <%= Phoenix.Controller.get_csrf_token() %>
1 Like