I want to show a current user’s name in the live.html.leex template using LiveView.
I’m setting the current user in an authentication plug with
put_session(:current_user, user)
I know in any other LiveView I’m supposed to
def mount(_params, %{"current_user" => current_user}, socket) do
{:ok, socket |> assign(:current_user, current_user)}
end
to be able to access @current_user
in the template, but for live.html.leex there is no opportunity anywhere to setup mount as far as I know?
My app was generated with the --live flag so my live.html.leex is rendered with MyAppWeb.LayoutView right? which is just a regular view so I can’t put a mount callback there.
Thanks for any help.
live.html.leex
is the default layout (unless you set a different layout yourself). Any assigns set in your main liveview will be available in live.html.leex
.
In your example, @current_user
would be available in live.html.leex
.
1 Like
Where would I set any assigns for live.html.leex
though? It gets rendered by MyAppWeb.LayoutView
, not a LiveView with a mount
callback, which extends :view
not :live_view
. I assume the --live
generator set it up this way for a reason so I don’t think I should try and change MyAppWeb.LayoutView
to achieve what I want but maybe i’m wrong.
live.html.leex
gets the assigns you set in whatever liveview is being rendered. The liveview with the mount
function you wrote in the 1st post would make @current_user
available in live.html.leex
.
1 Like
I’m having trouble with more or less the same issue. But I don’t understand where to write a mount function for a live.html.heex
template. Could someone make it a bit clearer for me?
You don’t write a mount function for live.html.heex
specifically. Instead, the regular mount
function of whatever page you are rendering handles setting assigns for live
. Basically, if you want to refer to an assign in live.html.heex
, you just set it in the pages that use that layout.
1 Like
Now you can use new on_mount
feature from liveview to assign current_user
in all of your live_views, at once.
defmodule CurrentUserHook do
import Phoenix.LiveView, only: [assign: 3]
use Common.Views.Helpers.Authentication
def on_mount(:default, _params, session, socket) do
user = current_user(session)
{:cont, assign(socket, :current_user, user)}
end
end
which you should use from your router
as such
live_session :default, on_mount: CurrentUserHook do
# your live routes
end
4 Likes