You can assign @current_path in both a plug and a LiveView hook (not to be confused with a js hook).
Plug:
defmodule MyAppWeb.Plugs do
import Plug.Conn
import Phoenix.Controller
def assign_current_path(conn, _) do
assign(conn, :current_path, current_path(conn))
end
end
…and add to your browser pipeline in the router:
MyAppWeb.Router do
# ...
import MyAppWeb.Plugs
pipeline :browser do
# ...
plug :assign_current_path
end
end
Live Hook:
defmodule MyAppWeb.LiveHooks do
import Phoenix.Component, only: [assign: 3]
import Phoenix.LiveView, only: [attach_hook: 4]
def on_mount(:global, _params, _session, socket) do
socket =
attach_hook(socket, :assign_current_path, :handle_params, &assign_current_path/3)
{:cont, socket}
end
defp assign_current_path(_params, uri, socket) do
uri = URI.parse(uri)
{:cont, assign(socket, :current_path, uri.path)}
end
end
…and attach the hook in your router:
live_session :some_name, on_mount: [{MyAppWeb.LiveHooks, :global}] do
# ...
end
(:global can be something more descriptive if you like)
Now @current_path is always available in the layout whether rendered by a live or dead view.
You can use these methods to stuff other data into assigns as well.
EDIT: I forgot the router portion for the plug… see above.
2ND EDIT: Sorry, @brady131313, I blew past your message that offered the same hook advice.






















