marcamillion
marcamillion

Reputation: 33755

How do I apply a style to a <span> if a condition exists, and take it away if it doesn't in Rails 3?

The span tag currently looks like this:

<span class='best_in_place<%= ' list-downvoted' if upload.downvoted? %><%= ' list-upvoted ' if upload.upvoted? %>'

However, if this span is both downvoted & upvoted, it applies both styles.

How do I modify this to only apply one, and get rid of the other if the other does exist?

i.e. if this item has been downvoted before, remove the list-downvoted class, and vice versa.

Edit: Added the recommended code in my UploadsHelper

module UploadsHelper
    def best_span_class_for_upload(upload)
      # Start with the base style
      css_class = 'best_in_place'

      # Add on any conditional styles using String#<< concatenation
      css_class << ' list-downvoted' if (upload.downvoted?)
      css_class << ' list-upvoted' if (upload.upvoted?)

      # Return the result
      css_class
    end
end

With the span looking like this now:

<span class='<%= best_span_class_for_upload(upload) %>' id='best_in_place_upload_name' data-url='<%= upload_path(upload) %>' data-object='upload' data-attribute='name' data-formType='input' data-activator='span#upload-edit-name-<%= upload.id %>'><%= upload.name %></span>

Upvotes: 1

Views: 897

Answers (1)

tadman
tadman

Reputation: 211590

This might be better to roll up into a helper method to avoid making a mess of your template:

<span class='<%= best_span_class_for_upload(upload) %>'>

Then the helper method defined in a helper/ defined module would look like this:

def best_span_class_for_upload(upload)
  # Start with the base style
  css_class = 'best_in_place'

  # Add on any conditional styles using String#<< concatenation
  css_class << ' list-downvoted' if (upload.downvoted?)
  css_class << ' list-upvoted' if (upload.upvoted?)

  # Return the result
  css_class
end

Update:

Revised version that shows only one of up or down:

def best_span_class_for_upload(upload)
  # Start with the base style
  css_class = 'best_in_place'

  # Add on any conditional styles using String#<< concatenation
  if (upload.downvoted?)
    css_class << ' list-downvoted' 
  elsif (upload.upvoted?)
    css_class << ' list-upvoted'
  end

  # Return the result
  css_class
end

Upvotes: 2

Related Questions