Phoenix Liveview render custom leex template

As you might have seen in Phoenix liveview multitenancy. I’m building an app that stores domains in database and based on domain it filters data from database and need to show different templates on different sites. This is pretty much universally deserved feature for this kind of use case.

But I could not find how to use different templates for different domains. If I have MyAppWeb.PageLive module I have to use page_live.html.leex. That’s not very cool. Because I went to render different template like other_sute.html.leex but now I’m not able to. Changing layout is not what I want right now. At least I don’t think it’s a good idea.

To change layout based on URI/domain I need to use live_render/3 from ordinary controller. Unfortunately I’m not able to get URI in mount/3. So it would be a littler cumbersome to convince Phoenix to use different layout based on URI. But I’m open for suggestions.

You can define a render/1 function that can, conditional on one of the assigns, render one of arbitrarily many views / templates.

2 Likes

OK this time RTFM was the right thing to do. I mean Collocating templates. The problem is I didn’t know how to define the view needed.

So Just in case someone has the same problem as me. Define page_live_view.ex that contains:

defmodule AppWeb.PageLiveView do
  use AppWeb, :view

end

Now you can define template in templates/page_live/page_live.html.leex or render("page_live.html") inside page_live_view.ex. Your choice. To make it all work you need to define render/1 function inside your live view.

def render(assigns) do
    Phoenix.View.render(AppWeb.PageLiveView, "page_live.html", assigns)
end

Of course you can render different templates based on the data you have in assigns.

5 Likes

What for liveview 0.20. what works in case of liveview 0.20?