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 Is there a way to do it without LiveComponents?
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
# Include shared imports and aliases for views
def live_view do
defp view_helpers do
# Add your helpers here
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
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:
- Define a custom
render function that tells LiveView the specific view and default file to render when mounted.
- Move the related LiveView “view file” (eg:
example_live.html.heex) file into the file you specify in the custom render function
- Render normal
html.eex partials within the LiveView just as you would on non-LiveView pages.
A quick example:
- Create the basic LiveView with the custom render function:
defmodule MyAppWeb.PlayerLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
# 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
- Make sure you create the related View if it does not already exist:
defmodule MyAppWeb.PlayerView do
use MyAppWeb, :view
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.
- You can then render other static (
.eex) partials within your LiveView, all while maintaining LiveView functionality:
<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
_sidebar.html.eex would live in the same
I hope this helps!