Creating Phoenix links outside template file

Hi,

I have a Phoenix template file where I want to list user notifications. There are different types of notifications and most of them link to some other page. Right now, i have a conditional logic which creates a link for each notification based on it’s type inside the template file and I was wondering if there is a better way, should I move it somewhere else, some helper perhaps? If so, how do I make it work, how do I create link outside of a template file?

This is what I have right now;

<%= for notification <- @notifications do %>
        <li class="">

          <%= cond do %>

            <% notification.entity_type == "complete_your_profile" -> %>
              <%= link "Complete your Profile", to: Routes.profile_path(@conn, :edit) %>

            <% notification.entity_type == "verify_your_account" -> %>
              <%= link "Verify your Account", to: Routes.user_confirmation_path(@conn, :new) %>

            <% true -> %>
              <%= notification.name %>

          <% end %>
        </li>
      <% end %>

Templates are just functions inside the view module. So all code there will be ran in context of your module. That mean that inside your view you can create function, for example:

def notification(conn, %{entity_type: "complete_your_profile"}) do
  link("Complete your Profile", to: Routes.profile_path(conn, :edit))
end

# Etc.

And then use that in your template.


BTW cond there looks really unidiomatic IMHO.

2 Likes