Rendering Template in Phoenix LiveView

Tracey Onim
1 min readMar 7, 2022

--

Today, I would like to share with you different ways in which phoenix LiveView renders template.

1. Rendering inside the LiveView

This usually happens when the render/1 callback is defined inside a LiveView module. The render/1 takes in an assign map and returns a template via Phoenix.LiveView.Helpers.sigil_H/2 .

Example :

defmodule MyAppWeb.SampleLive do
use MyAppWeb, :live_view
def render(assigns) do
~H"""
My name is <%= @name %>
"""
end
end

2. Rendering in the same directory as the LiveView

This is done by placing the file of the template in the same directory as the Liveview and using the same name as the LiveView.

Example:

You can place your LiveView file at lib/my_app_web/live/sample_live.ex and put your template code at lib/my_app_web/live/sample_live.html.heex.

lib/my_app_web/live/sample_live.ex:defmodule MyAppWeb.SampleLive do
use MyAppWeb, :live_view
end
lib/my_app_web/live/sample_live.html.heex:My name is <%= @name %>

Note: While using this strategy, you don’t have to define render/1 inside the LiveView . If defined, it will take precedence and hence the content added to the template file(i.e lib/my_app_web/live/sample_live.html.heex) won’t be displayed.

3. Delegate to an existing Phoenix.View

In this case, you will maintain defining the render/1 in LiveView module but delegate to an existing Phoenix.View.

Example:

defmodule MyAppWeb.SampleLive do
use MyAppWeb, :live_view
def render(assigns) do
Phoenix.View.render(MyAppWeb.PageView, "page.html", assigns)
end
end

Here you will have your template file placed inside lib/my_app_web/templates/page/page.html.heex and Phoenix view at lib/my_app_web/views/page_view.ex

You can always use any of the strategies stated above according to your preference. For larger template files I would recommend 2 and 3 .

I hope you’ll find this post helpful. Happy Coding !!!

--

--

Tracey Onim

Backend software developer, Programming with Elixir/Phoenix/LiveView. Community organiser at ElixirKenya & ElixirConfAfr