Elliot
Elliot

Reputation: 2289

Layout refactoring

I can't help but thing there is a better way of coding the below in a Rails layout. Any suggestions?

<% if remove_ads_from_page? %>
   <div class="main-content without-ads">
    <%= yield %>    
   </div>
<% else %>
   <div class="main-content with-ads">
    <%= yield %>
   </div>
<% end %>

Upvotes: 2

Views: 120

Answers (3)

Mike Silvis
Mike Silvis

Reputation: 1309

Elliot there are a couple ways to take logic out of a rails view. One of the simplest ways is to use the gem draper

http://railscasts.com/episodes/286-draper

Another thing you could do is consider using HAML to clean up your view.

Upvotes: 0

Pierre
Pierre

Reputation: 8348

How about

   <div class="main-content <%= remove_ads_from_page? ? 'without' : 'with' %>-ads">
    <%= yield %>    
   </div>

Upvotes: 1

varatis
varatis

Reputation: 14740

<% if remove_ads_from_page? %>
   <div class="main-content without-ads">
<% else %>
   <div class="main-content with-ads">
<% end %>
    <%= yield %>
   </div>

This should work. Rails doesn't care that your html tags are properly closed in between if and else clauses. This just says, "If remove_ads_from_page is true, then print out this snippet. Otherwise, print out this snippet."

Upvotes: 0

Related Questions