Conditional Variables in Phoenix Templates
A common Ruby on Rails technique is setting instance variables in a controller action, then using them in the view layer:
# app/controllers/users_controller.rb
def show
@show_button = true
end
# app/views/users/show.html.haml
- if @show_button
.button
Doing the same thing in Elixir/Phoenix is a little different.
Since Phoenix 0.14.0, the framework raises on missing assigns (link). Thus our conditional will fail on any loaded template whose controller function that does not define the variable.
One solution is to check if the variable is assigned:
# lib/my_app_web/templates/users/show.html.eex
<%= if assigns[:show_button] do %>
<div class="button"></div>
If show_button
is assigned in your controller function (via assign
), the button will be displayed. If not, the button will not be displayed, and the application will not raise an error.