I’ve got a Rails 3 application where I’m using quite a few conditional statements to change the design of the page. What is the best practice for keeping the logic out of the view for having such drastic amounts of conditionals?
Hypothetical Example:
<% unless @ethos.blank? %>
<%= unless @work.nil? do %>
<%= link_to "Add Work", work_path %>
<% end %>
<%= @ethos.tagline %>
<% end %>
I’ve got many more conditionals inside of other conditionals. What is the best way to manage this inside of one view?
You should avoid complex conditionals (and most conditionals) in views. Extract them to a Helper, or better yet, to some kind of “presenter” so that you can work with a receiver instead of those “global looking/feeling helpers”
SomeHelper
View
If
@ethosis likely to benilas opposed to an empty[]array, you could instead use:Also note that in your original view
<%= unless @work.nil? do %>should have been using a-and not a=.Oh, and I encourage you to use HAML over ERB. With HAML, the view looks like this (easier to read, isn’t it) :
Your original view would look like this in HAML (remember, avoid conditionals in views as much as possible!)