I’d like one of my LiveView’s to use a separate stylesheet all together, rather than the default styles included in the root layout, which I use on the rest of the pages in the app. I’m having trouble figuring out the best way to do that. I know you can make additional layouts (like the app layout), but those are still rendered within the root layout.
Note: If you find yourself needing to dynamically patch other parts of the base layout, such as injecting new scripts or styles into the <head> during live navigation, then a regular, non-live, page navigation should be used instead.
I think that’s a bit different than what I’m going for – I don’t need the stylesheet to change dynamically, I just want to initially render the LV page with one that’s special. Also, I guess you can include a link tag for a stylesheet directly in the body, but that’s “bad practice” according to MDN, also I don’t want the other stylesheet, which would still be included in the root layout.
I solve that with different root layouts, but that’s in the docs you linked, maybe it doesn’t work for you? eg:
pipeline :public do
plug :browser
plug :put_root_layout, {Public.Layouts, :root}
end
pipeline :admin do
plug :browser
plug :put_root_layout, {Admin.Layouts, :root}
end
You’ll also have to define the “landing” and other routes in separate live_session so the head data is renewed.
I know you’re only swapping the CSS, so a whole new layout might feel over done. You can dedupe what you need between both root layouts into functions but I find they generally end up sharing little, over time.
You can alternatively define a functional component (in core_components.ex would work in a default phx.new) and call that in <head>, again using live_session to enforce the change. Note we use assigns[] access, so it defaults to nil if no value is set.
<head>
<.css name={assigns[:css_key]} />
</head>
def css(%{css_key: "landing"} = assigns) do
~H"""
<link phx-track-static rel="stylesheet" href={~p"/assets/special.css"} />
"""
end
def css(assigns) do
~H"""
<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
"""
end
You can assign css_key either directly in the liveview on_mount (or related hooks) or in a plug by inspecting conn or passing what you want via opts.
You’ll also have to define the “landing” and other routes in separate live_session so the head data is renewed.
I cant edit my post, it’s been a while since I wrote LV stuff but the pedant in me wants to say you can just use regular navigation to force the same thing as the docs say. The session blocks is not actually a requirement.
My stuff just happens to be in different live_session blocks because they always end up running different plugs/hooks so that’s my habit. The live_session will also force a reload in case you accidentally use LV navigation instead too.