Calling Elixir function in a layout

When I need to insert some Elixir code into a layout, what’s the idiomatic way to do this? In particular, how can I do aliasing so that I don’t need to call a function using its long name which includes all the modules?

For example:

# layouts/app.html
<!-- some stuff -->

<%= if MyApp.Module1.Module2.Module3.func1(@conn) === true %>
  <!-- some stuff 2 -->
<% end %>
  1. First of all, how can I do aliasing of if MyApp.Module1.Module2.Module3 so that I can say merely Module3.func1(@conn) ? I don’t want to add an alias into web.ex because I might need to call this function only in a single place.

  2. And also, maybe I should call if MyApp.Module1.Module2.Module3.func1(@conn) === true somewhere in an *.ex file such as a view so that in I can just say something like this in app.html:

    <%= if my_predicate?(@conn) === true %>

    <% end %>

On the other hand, I’ll still to call it using its long name MyApp.LayoutView.predicate?(@conn), right? that is, there’s no reason.

Your advice, I’m confused.

If I recall correctly, a template is evaluated in the context of its view. So every import, require or alias you do there should be visible in the template as well.

2 Likes