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

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)

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

  def view do
quote do
import SampleAdmin.Helpers

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.

  h1= assigns[:title]

  = if assigns[:body] do
        = assigns[:body].()

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



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