Let's say I have something like this:
defmodule MyAppWeb.Live.PostComponents do
use Phoenix.Component
use Phoenix.HTML
def card(assigns) do
~H"""
<div class="row ....">
<nav class="......"></nav>
<%= live_redirect "...", to: @content.slug, class: "stretched-link" %>
<%= if do %>
blah-blah-blah-blah-blah-blah
<% end %>
</div>
"""
end
How to move this code into an html or *.heex file to then call render(....) somehow? The end result must remain the same.
You can embed *.html.heex
files into function components with embed_templates/1
see LiveView docs here.
The template code can be put into a card.html.heex
file (by convention the template files can be moved to separate directory near your module, e.g. /pages/card.html.heex
. In your MyAppWeb.Live.PostComponents
you then call embed_templates/1
on module level with the path to the template folder as an argument and MyAppWeb.Live.PostComponents
will have a function component card
defined.
defmodule MyAppWeb.Live.PostComponents do
use Phoenix.Component
embed_templates "pages/*.html.heex"
end
# somewhere else in another template or render function
~H"""
...
<MyAppWeb.Live.PostComponents.card ... >
...
<./MyAppWeb.Live.PostComponents.card>
...
"""
For more information on declarative assigns of function components embedded like this see the embed_templates/1
documentation.