If else comprehension in elixir expressions (phoenix templates)

Is it possible to have a ternary if statement in phoenix template’s elixir expression?

A good use case for this is using 1 of 2 assigns in a comprehension. This saves from duplicating the same HTML or referencing a partial template under each if else condition.


<%= if @formatted_things != nil, do: for thing <- @formatted_things, else: for thing <- @unformatted_things %>
 <%= thing.name %>
 <%= thing.age %>
 <%= thing.whatever %>
<% end %>

As if/2 is already an expression, there is no need for ?:. Yes its a bit more verbose, but it does work the same.

2 Likes

I think a simpler solution might be to select the source in for. Additionally you could use || in this case. But otherwise if(@formatter_things != nil, do: @formatted_things, else: @unformatted_things) also works as an expression.

<%= for thing <- @formatted_things || @unformatted_things do %>
 <%= thing.name %>
 <%= thing.age %>
 <%= thing.whatever %>
<% end %>
5 Likes