root

root

Hello everyone.

I have an app that’s going to be setting the layout dynamically according to the current domain name. I’m trying to figure out a way to do it in LiveView.

I’ve gotten to the point where I have an on_mount helper that gets the current hostname and makes it available in assigns, but I’m not able to use that from within the LiveView mount calls, because the helper depends on hooking handle_params. The only other place to set the layout (as far as I know) is in the router or in the myapp_web file where the :live_view helpers are defined, and I’m not seeing how to get access to the hostname from either of those locations.

Is there a recommended way to do this that I’ve missed?

Showing Posts 1 to 10

sodapopcan

sodapopcan

I’m assuming you have a fixed number of subdomains since you probably aren’t going to have an infinite number of layouts :sweat_smile:

There are a few ways to do this. My current project is an online store which has a “retail” layout (for the main domain) and an “admin” layout (for the backoffice admin. subdomain).

I’m currently doing it like this:

In MyAppWeb, ie, in lib/my_app_web.ex I have:

  def admin_live do
    quote do
      use Phoenix.LiveView,
        layout: {MyAppWeb.Layouts, :admin}

      unquote(html_helpers())
    end
  end

  def retail_live do
    quote do
      use Phoenix.LiveView,
        layout: {MyAppWeb.Layouts, :retail}

      unquote(html_helpers())
    end
  end

In lib/my_app_web/components/layouts/ I add an admin.html.heex and retail.html.heex. The :admin in {MyAppWeb.Layouts, :admin}, for example, corresponds to admin.html.heex.

Then in my LiveView, instead of use MyAppWeb, :live_view I do use MyAppWeb, :retail_live and use MyAppWeb, :admin_live.

They do both share the same root layout which is very generic.

I’m happy with my solution but I’d also be interested in hearing how others do this!

sodapopcan

sodapopcan

Sorry, I think I may have misunderstood what you’re asking. Do you have multiple domains pointing the same LiveView and want the layout to change based on that? In that case I’m not sure it’s possible as I believe the only place to set it is when calling use LiveView, layout: {Mod, :file}. I could be wrong but can’t find anything in the docs and there is this post from José. It’s 2 years old so maybe something’s changed?

There may be a way. What does your router look like?

root

root OP

I’m assuming you have a fixed number of subdomains since you probably aren’t going to have an infinite number of layouts :sweat_smile:

I have a theoretically infinite set of domain names, not just subdomains, to support, but they map to a small, fixed set of themes.

The docs state the layout can be set from the router in the live_session, and from the mount(). I detailed why the mount() approach hasn’t panned out in the OP, and I’m not sure how to get the host information I need into the router to do it from the live_session.

My router right now mostly has the admin routes defined which are exempt from this whole thing. I’ve been working on them while searching for a way to accomplish this. Nothing but a test liveview defined for the public area, and the helpers that I’ve confirmed grab the host and the configuration from my database.

scope "/", MyAppWeb do
    pipe_through [:browser, :do_config]

    # login not required
    ash_authentication_live_session :authenticated_optional,
      on_mount: [
        {MyAppWeb.LiveUserAuth, :live_user_optional},
        {MyAppWeb.AssignUrl, :save_request_uri},
        {MyAppWeb.AssignConfiguration, :assign_configuration}
      ] do

      live "/", PublicLive.Index, :index
    end
    ...
    # other routes
    ...
end

I was using plugs when I had this idea working a while ago in deadviews. The same strategy hasn’t worked in 1.7+ and with LiveViews.

I’m sure there’s some way!

sodapopcan

sodapopcan

So apart from :temporary_assigns, it looks like mount/3 also accepts a :layout option! So I think you could figure out the layout in your on_mount then grab it from the socket in mount/3 and return it like: {:ok, socket, layout: socket.assigns.layout}. I haven’t actually tried this or anything but that is my best guess. The only thing is that you’ll have to repeat that for every LiveView which probably isn’t the biggest deal.

root

root OP

That’s what I’m currently attempting to do, but it looks like mount/3 happens before handle_params which is where my helper is grabbing the url

defmodule MyAppWeb.AssignUrl do

  def on_mount(:save_request_uri, _params, _session, socket),
    do:
      {:cont,
       Phoenix.LiveView.attach_hook(
         socket,
         :save_request_path,
         :handle_params,
         &save_request_path/3
       )}

  defp save_request_path(_params, url, socket) do
    socket =
      socket
      |> Phoenix.Component.assign(:current_uri, URI.parse(url) |> Map.get(:path))
      |> Phoenix.Component.assign(:current_host, URI.parse(url) |> Map.get(:host))

    {:cont, socket}
  end

So the information I need (the current host) isn’t yet accessible during mount. Unless there’s another way to access it than the current strategy I found here (in a discussion about styling the active nav link)

olivermt

olivermt

Can you not set up a plug that puts the host in the session?

sodapopcan

sodapopcan

Wellllllll ****. Could you add it to the session from a plug so it’s available in mount? Maybe not ideal. I don’t think I can be much help here as I’ve never actually done this myself. I’m interested, though, so hopefully someone else can help!

(and yes, I also read that same thread and how I set the current URL too :slight_smile: )

EDIT: Ha, re: post that beat me to the punch

root

root OP

This actually works! Thank you both! Let me clean it up a bit and make sure I understand it and then I’ll post the full working thing. Are there any downsides or ramifications I should be aware of with regards to storing this in the session? Is this session data modifiable by the user? Going through the docs now

My proof of concept right now is using String.to_atom which i understand comes with some concerns, but layout: demands an atom in Phoenix 1.7+

sodapopcan

sodapopcan

Session is definitely modifiable by user so if that’s a concern that prob won’t work. It’s further less desirable with String.to_atom as it opens you up to an attack.

The other option here is to use components instead of the layout files. You could load the layout name in handle_params then have a component that delegates to the proper layout component.

attr :name
slot :inner_block
def layout(assigns) do
  ~H"""
  <%= case @name do %>
    <% "admin" -> %><.admin_layout><%= render_slot(@inner_block) %></.admin_layout>
    <% "some_other" -> %><.some_other_layout><%= render_slot(@inner_block) %></.some_other_layout>
    <% ... %>
  <% end %>
  """
end

then in your LiveView:

def render(assigns) do
  ~H"""
  <.layout name={@layout_name_set_in_handle_params}>
    <h1>Hi!</h1>
  </.layout>
  """
end

I would probably pattern match in function heads over that case statement, but you get the gist.

If you were using Surface you could use dynamic components though I’ve never used those so can’t give an example.

EDIT: Just for completeness I meant this as an alternative to the case:

def layout(%{name: "admin"} = assigns) do
  ~H"""
  <.admin_layout>
    <%= render_slot(@inner_block) %>
  </.admin_layout>
  """
end

def layout(%{name: "some_other"} = assigns) do
  ~H"""
  <.some_other_layout>
    <%= render_slot(@inner_block) %>
  </.some_other_layout>
  """
end

sodapopcan

sodapopcan

And to be clear I meant like they could potentially manipulate the session based on the hostname. If you are whitelisting hostnames then it’s no problem.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews