marcamillion
marcamillion

Reputation: 33755

Why does my content_tag not produce the HTML I expect?

I am rendering my Profiles#Index view. In that view, I call this helper method:

<%= ratings_labels(profile, params[:rating]) %>

That is defined in profiles_helper.rb, like so:

def ratings_labels(profile, rating_param)
    rating_classes = {
      'speed'     => 'label label-success label-lg',
      'tackling'  => 'label label-info label-lg',
      'passing'   => 'label label-warning label-lg',
      'dribbling' => 'label label-primary label-lg'
    }

    rating_classes.each do |rating, klass|


      content_tag :div, class: "col-lg-3" do
        content_tag :span, class: "#{klass}" do
          "#{rating.capitalize}: #{profile.ratings.find_by(user: current_user)[rating]}"
        end
      end
    end

     end
  end

However, what the outputs in my HTML is this:

{"speed"=&gt;"label label-success label-lg", "tackling"=&gt;"label label-info label-lg", "passing"=&gt;"label label-warning label-lg", "dribbling"=&gt;"label label-primary label-lg"}

Notice there is no HTML generated. No div.col-lg-3 or span.

Why is that?

Upvotes: 0

Views: 221

Answers (1)

Shiva
Shiva

Reputation: 12514

Try this, this should work

  def ratings_labels(profile, rating_param)
    rating_classes = {
        'speed'     => 'label label-success label-lg',
        'tackling'  => 'label label-info label-lg',
        'passing'   => 'label label-warning label-lg',
        'dribbling' => 'label label-primary label-lg'
    }

    markup = ''

    rating_classes.each do |rating, klass|
      markup << content_tag(:div, class: "col-lg-3") do
        content_tag :span, class: "#{klass}" do
          "#{rating.capitalize}: #{profile.ratings.find_by(user: current_user)[rating]}"
        end
      end
    end

    markup.html_safe

  end

You have to record the output of individual loop and aggregate to get the desired output. Also html_safe makes your string to be clean to be rendered in browser as valid HTML.

Notice there is no HTML generated. No div.col-lg-3 or span.

Your helper method is returning the hash rating_classes as it is the last statement in the method(ruby feature you see). While rendering ruby executes .to_s methods in every object.

Upvotes: 1

Related Questions