Link to liveview from regular template


I feel that I’m missing a simple yet important piece. I’m struggling to write a link in a regular template file to a live_path because I don’t know how to get @socket or if I’m doing it right at all…

In my router I have the following entry:

live /some/path, PageLive

then in a template .heex I’d like to link to that view with a <%= link "visit", to: Routes.live_path(@socket, PageLive) %> but I don’t know how to get the @socket… Or maybe I’m doing it completely wrong?


With the new Verified Routes functionality introduced in Phoenix v1.7, you can do something like this:

<.link to={~p"/some/path"}>Some LiveView</.link>

If that’s not available, it’s possible with the live_path helper to do something like this:

iex> MyApp.Router.Helpers.live_path(MyApp.Endpoint, MyApp.ThermostatLive)

# assuming the following router
defmodule MyApp.Router
  use Phoenix.Router
  import Phoenix.LiveView.Router

  scope "/", MyApp do
    pipe_through [:browser]

    live "/thermostat", ThermostatLive
    live "/clock", ClockLive
    live "/dashboard", DashboardLive, container: {:main, class: "row"}

source: Phoenix.LiveView.Router — Phoenix LiveView v0.18.18


Thank you. The second option worked.

I have a question to the first option, though: hardcoding the path seems kind of not the way to go. What is the reasoning behind this?

It may seem like you’re just hardcoding the path, but thanks to the ~p sigil, you’re actually getting compile time verified routes.

This has a number of advantages. There’s no longer guesswork on which function was inflected – is it Helpers.oauth_callback_path or o_auth_callback_path, etc. You also no longer need to include the %Plug.Conn{}, or %Phoenix.Socket{}, or endpoint module everywhere when 99% of the time you know which endpoint configuration should be used.

There is also now a 1:1 mapping between the routes you write in the router, and how you call them with ~p. You simply write it as if you’re hard-coding strings everywhere in your app – except you don’t have maintenance issues that come with hardcoding strings. We can get the best of both worlds with ease of use and maintenance because ~p is a compile-time verified against the routes in your router.

source: Phoenix 1.7.0 released: Built-in Tailwind, Verified Routes, LiveView Streams, and what's next - Phoenix Blog