Profile picture Schedule a Meeting
c a n d l a n d . n e t

Elixir Phoenix Partials

Dusty Candland | | elixir, phoenix

How to create partials in Elixir with block like syntax. Like:

= render_shared "page_header.html", title: "Listing Posts", body: fn ->
  = link "New Post", class: 'btn btn-sm btn-outline-secondary', to: post_path(@conn, :new)

Create a SharedView module to hold the shared templates.

defmodule SampleAdmin.SharedView do
  use SampleAdmin, :view
end

Create a Helpers module that we'll add to all views. This is where we'll create the render_shared function.

defmodule SampleAdmin.Helpers do
  alias Phoenix.View

  def render_shared(template, assigns \\ []) do
    View.render(SampleAdmin.SharedView, template, assigns)
  end
end

Add Helpers to all Views in the root module SampleAdmin in this case.

  def view do
    quote do
      ...
      import SampleAdmin.Helpers
    end
  end

Create the shared template in templates/shared. In here you need to check if the body was assigned & if so then render the output by calling the function. Could probably make sure it is a function in the render_shared function.

.d-flex.justify-content-between.flex-wrap.flex-md-nowrap.align-items-center.pt-3.pb-2.mb-3.border-bottom
  h1= assigns[:title]

  = if assigns[:body] do
    .btn-toolbar.mb-2.mb-md-0
      .btn-group.mr-2
        = assigns[:body].()

The SharedView & Helpers setup is optional, but I like having them setup.

References

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: