Creating conn.assigns is available in several Phoenix views / templates.

I need a user authentication token defined in SessionController , which will be available in layout/app.html.eex .

My SessionController defines the token and assigns it to conn .

 token = Phoenix.Token.sign(conn, "user socket", user) assign(conn, :user_token, token) 

Then, when I try to use the token in app.html.eex , as shown below,

  <script>window.userToken = "<%= assigns[:user_token] %>"</script> or <script>window.userToken = "<%= @user_token %>"</script> 

I get this error: (ArgumentError) assign @user_token not available in eex template.

+5
source share
1 answer

conn.assigns are reset for each request. If you want to save something in the SessionController and have it in future requests, you can use put_session ;

In your SessionController:

 token = Phoenix.Token.sign(conn, "user socket", user) conn |> put_session(:user_token, token) |> render(...) 

Then, to access it in other controllers, you can use:

 token = get_session(conn, :user_token) 

To access it in several templates, you can add a plugin to the appropriate pipeline (s) in your router:

 pipeline :browser do ... plug :fetch_user_token end ... def fetch_user_token(conn, _) do conn |> assign(:user_token, get_session(conn, :user_token)) end 

Now you can access the token in any template using @user_token (or assigns[:user_token] or assigns.user_token or @conn.assigns[:user_token] or @conn.assigns.user_token ), the same will be shown here result).

+6
source

Source: https://habr.com/ru/post/1261077/


All Articles