LiveView: set nonlive layout

LiveView can use “live” layouts now, via providing option :layout to the module.
By default it does use regular, non-live layout like app.html.

The question is, is there a way to make LiveView use other, non-live layout? like “admin.html”

live version do not support @conn and such and rewriting (for existing project) it to remove @conn calls somehow would be time consuming

1 Like

Hey @thousandsofthem,

This is possible but it isn’t exactly intuitive. Basically, you need to change the root layout at the plug level, and not the live view level. eg:

pipeline :admin do
  plug :set_layout, template: "admin.html"
end

defp set_layout(conn, opts) do
  conn |> put_layout(opts[:template])
end

scope "/admin" do
  pipe_through [:browser, :admin]
  live "/users", SomeliveView
end

scope "/" do

  # other things here
end

Basically, when you set the layout within the world of live view, you’re really setting a sort of “sub” layout that runs inside and after the root one set in plug. If you want to change the root entirely because you need to use the @conn then you need to swap that out at the plug level.

4 Likes

It worked! Thank you!
Never knew this trick.

P.S. Small correction for other readers:

plug :set_layout, template: {AppWeb.LayoutView, "admin.html"}

(where name AppWeb is the project’s web name)

2 Likes

With the developing version 0.8.2-dev, we can use put_live_layout, the Liveview use the “separated static” layout and not inherited from app.html.

3 Likes
  1. Create a pipeline function in router.ex:
pipeline :full_screen_layout do
  plug(:put_root_layout, {MyWeb.LayoutView, :deadview})
end
  1. Pipe it in the scope of routes:
# Public browser routes
  scope "/", MyWeb do
    pipe_through [:browser, :redirect_if_user_is_authenticated, :full_screen_layout]
  1. Create ur :deadview that you declare within the tuple with MyWeb.LayoutView:
touch ./lib/my_web/templates/layout/deadview.html.heex

Just sharing what I did and feel free to let me know how can I do it better!

Best wishes,
Jing Hui P.