Adding Global View Helpers to a Phoenix Application

Posted by in Phoenix, last updated on 06 September, 2020

Introduction

If you come from a Ruby on Rails background you might be used to having view helpers such as number_with_delimiter up your sleeve and ready to use in any view.

Here’s how to configure functions that are accessible in your Phoenix views:

1) Create a helper module

I usually create a helpers directory under the app_name_web directory. Next create a new module, let’s call it application_helper.ex:

defmodule YourApp.ApplicationHelper do
  def number_with_delimiter(integer) do
    integer
    |> Integer.to_char_list
    |> Enum.reverse
    |> Enum.chunk_every(3, 3, [])
    |> Enum.join(",")
    |> String.reverse
  end
end

2) Import your helper module

If we want call these functions without prepending the module name (number_with_delimiter instead of ApplicationHelper.number_with_delimiter), then we need to import the module.

You could import it in the view module for the views you’re about to use it in, however if we want the function available to us in any view then we need to import it in lib/your_app_web.ex instead:

def view do
    quote do
      ...

      # Import custom helpers here
      import YourAppWeb.ApplicationHelper
    end
  end
end

Now you can call the function in any of your views:

<ul>
  <%= for user <- @users do %>
    <li><%= user.age_in_days |> number_with_delimiter %></li>
  <% end %>
</ul>

That’s all there is to it!


Daniel Wachtel

Written by Daniel Wachtel

Daniel is a Full Stack Engineer who outside work hours is usually found working on side projects or blogging about the Software Engineering world.