hot tip 🔥Nested Elements using Phoenix HTML Helpers

How to deal with nested elements when using Phoenix's HTML Helpers

Something I ran into early on when using Phoenix + LiveView HTML helpers is how to deal with styling elements such as live_patch links when we want to have elements nested inside the element our HTML helper produces.

Although it's obvious once you know it, when first learning Phoenix and EEx / LEEx templates there weren't any explicit examples I saw doing this. Though there were some hints in the docs (seen below).

For example, let's say you're using a helper like live_patch to create a link. If you were using just html + talwindcss you might be looking at something like this:


<a href="#" class="bg-gray-100 text-gray-900 group flex items-center px-2 py-2 text-base font-medium rounded-md">
    <svg class="text-gray-500 mr-4 h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
    </svg>
    Dashboard
</a>

Here we have an anchor tag with an SVG Logo inside of it.

Most examples you'll see using Phoenix HTML Helpers will look something like this:


<%= live_patch to: Routes.dashboard_index_path(@socket, :index), class: "text-gray-900 group flex items-center px-2 py-2 text-base font-medium rounded-md" %>

We can pass class names and/or styles in our list of options, but it might not be immediately obvious how we could nest other html elements inside the anchor tag live_patch creates.

However if we take a look at the docs for live_patch or for something like link, we'll see they have an example using a do/end block.


<%= live_patch to: Routes.live_path(@socket, MyLive, dir: :asc), replace: false do %>
  Sort By Price
<% end %>

And we can totally add other elements inside this block to add things like SVG icons:


<%= live_patch to: Routes.dashboard_index_path(@socket, :index),
    class: "text-gray-900 group flex items-center px-2 py-2 text-base font-medium rounded-m" 
    do %>
        <svg class="text-gray-500 mr-3 h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
        </svg>
    Dashboard
<% end %>

And voila! 👏 you have nested html in your Phoenix + LiveView HTML Helpers!

Keep in mind this works with the form label & input helpers as well!