Passing login user data to html view

Trying to figure out the best way to pass in logged user data like name and email to my header view?

I have the following inside my admin view, which renders the header HTML

<%= render MagnifyWeb.AdminSharedView, “_header.html”, assigns %>

And this for the shared view

defmodule MagnifyWeb.AdminSharedView do
  use MagnifyWeb, :view
end

Is the data in assings? If so, you can access it from within the _header.html.eex template.

1 Like

No its not there

So,

Assuming you have a authentication system in place to handle your users, you normal store the users data in the session store to keep track. You can find the default stores Phoenix includes here: https://hexdocs.pm/plug/1.4.5/Plug.Session.html

Assuming you use the Plug.Session.Cookie, your authentication system should use the methods Plug.Conn.put_session/3 and Plug.Conn.get_session/3 to save the users information and fetch it respectively. You can find more information here: https://hexdocs.pm/plug/1.4.5/Plug.Session.COOKIE.html and https://hexdocs.pm/plug/1.4.5/Plug.Conn.html#put_session/3

The users information will be stored in the session and can be fetch in the html page using the connection (conn).

You can also store the user information elsewhere and send the users information in the assigns map inside the conn struct as @idi527 suggested . You can find more information here: https://hexdocs.pm/plug/1.4.5/Plug.Conn.html. You can add the users information in the assigns map when you render the page. Check the render/3 method here: https://hexdocs.pm/phoenix/Phoenix.Controller.html#render/3

Hope this helps.

Best regards,

1 Like

Not sure I understand I tried the following but its not working I take it I’m doing something wrong

 <!-- Header -->
        <%= render MagnifyWeb.AdminSharedView, "_header.html", assigns, title: "test" %>
         <!-- Header end -->

In header
<%= title(@conn) %>

Ok I think I got, new to Elixir so still getting the basics

need to do it via the view

So I’m getting the following error "protocol Phoenix.HTML.Safe not implemented for %Magnify.Coherence.User{meta: #Ecto.Schema.Metadata<:loaded, “users”>, "

I have the following in my view

def name(conn) do
    case conn.assigns[:current_user] do
      nil -> ""
      name -> name
    end
  end

And in my header

<%= name(@conn) %>

Any ideas?

All good got it working

1 Like