Elixir/Phoenix partials

Stan Bright
May 22, 2017 · 2 min read

This is going to be a very short post. Its intention is to help fellow Ruby on Rails developers who are exploring the new Elixir/Phoenix world.

First, there aren’t “partials” in Phoenix as we know them in Rails. As most parts of Phoenix, things are more explicit. You just render a template in the context of a specific “View” module. That’s all.

i.e. if you had this in Rails

# i.e. if you had a partial rendering like this on in Rails:
<%= render "jobs", jobs: @jobs %>
# you would have this equivalent in Phoenix
<%= render Myapp.Web.JobsView, "_jobs.html", jobs: @jobs %>
# or
<%= render Myapp.Web.JobsView, "_jobs.html", assigns %>

The Phoenix code above would simply use the “context” of the JobsView, and render the content from within “web/templates/jobs/_jobs.html.eex” template. It’s a bit more explicit and a bit more typing; however, in most cases that explicitness helps on the long run.

What about shared partials that are used across most pages? For example, a “sidebar” template. Well, then, what the official guides advise us is to add a simple SharedView module and put all shared templates in, you guessed it, the shared subfolder — “web/templates/shared” (you have to created it).

Then, you can use it like this:

# web/views/shared_view.ex
defmodule Myapp.Web.SharedView do
use Myapp.Web, :view
# web/views/shared/sidebar.html.eex
<div>SIDEBAR content</div>
# web/layouts/app.html.eex
<%= render Myapp.Web.SharedView, "sidebar.html", assigns %></sidebar>

That’s not too bad. Yet, as these are supposed to be “shared” templates that are used a bit more often throughout the app, we can simplify things a bit further by adding a “helper” function “render_shared” like this:

# web/web.ex
def view do
def render_shared(template, assigns \\ []) do
render(Myapp.Web.SharedView, template, assigns)
# then instead of
<%= render Myapp.Web.SharedView, "sidebar.html", assigns %>
# we can use "render_shared"
<%= render_shared "sidebar.html", assigns %>
<%= render_shared "job.html", job: job %>
# etc

All of this isn’t rocket-science, yet, I am sure it could be helpful to people that are just starting with Phoenix 😎. Cheers 🍻.

p.s. remember that Phoenix templates are compiled to functions that use IO Lists — i.e. they are super fast. So, use them as much as you want. I haven’t benchmarked them, but they are regarded to be times faster then Rails’ partials.

p.p.s. shameless plug — if you are into Elixir/Phoenix, you may find Awesome Elixir @ LibHunt helpful as well.

Stan Bright

Written by

Software Engineer. Founder of LibHunt, SaaSHub & EarlyRisersHub. Ruby on Rails expert. Elixir enthusiast.