Render static partial inside LiveView

Hi,

Is there a way to render a partial template in LiveView? I know there are LiveComponents but in my case, LC is too much I only need to extract some Html with variables to a parital in order to keep my main .leex file smaller. I tired render but it doesn’t exist in LiveView :frowning: Is there a way to do it without LiveComponents?

best regards
Piotr

You can define helpers, working under both normal, or LV…

If You look at your app_web.ex file, You will see something like

  def view do
    quote do
      ...
      # Include shared imports and aliases for views
      unquote(view_helpers())
    end
  end

  def live_view do
    quote do
      ...
      unquote(view_helpers())
    end
  end

  defp view_helpers do
    quote do
      ...
      # Add your helpers here
      import AppWeb.YourHelpers
    end
  end

Then, You can add your own in view_helpers() function

Thank you. I Haven’t thought about the helpers. I will try to write some custom render_partial function myself :slight_smile:

1 Like

It’s easy to render static .eex partials (non-LiveView components) within a LiveView. It takes a short bit of code rearrangement, but I’ve been using it often throughout my projects.

Short summary of steps:

  1. Define a custom render function that tells LiveView the specific view and default file to render when mounted.
  2. Move the related LiveView “view file” (eg: example_live.html.heex) file into the file you specify in the custom render function
  3. Render normal html.eex partials within the LiveView just as you would on non-LiveView pages.

A quick example:

  1. Create the basic LiveView with the custom render function:
defmodule MyAppWeb.PlayerLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, socket}
  end

  # Specify the "view" that Phoenix needs to render the partials (in this case PlayerView), and give it the default template to load.
  # (`show` would have been the related "player_live.html.heex" code if I had stuck with convention)
  def render(assigns) do
    MyAppWeb.PlayerView.render("show.html", assigns)
  end
end
  1. Make sure you create the related View if it does not already exist:
/lib/my_app_web/views/player_view.ex:

defmodule MyAppWeb.PlayerView do
  use MyAppWeb, :view
end

show.html.heex would then live under /lib/my_app_web/templates/player/show.html.heex. Make sure show.html.heex has the “.heex” extension.

  1. You can then render other static (.eex) partials within your LiveView, all while maintaining LiveView functionality:
# show.html.heex:
<div class="container">
  <div class="h-full md:h-screen">
    <div class="md:grid grid-cols-12">
      <div class="col-span-12 sm:col-span-12">
        <%= render "_sidebar.html" > # This is a static `.eex` partial
      </div>
    </div>
  </div>
</div>

_sidebar.html.eex would live in the same /lib/my_app_web/templates/player/ folder.

I hope this helps!