Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this nested content_tag not render properly?

I have this in my helper:

  def favorites_count(node)
    content_tag :span, class: "card-favorite-count" do
      content_tag :i, class: "icon-heart"
      node.cached_votes_total
    end
  end

That is being called like this in the view:

<%= favorites_count(node) %>

And that renders this:

<span class="card-favorite-count"></span>

How do I get it to render the entire thing?

Edit 1

Per @tolgap's suggestion below, I tried this:

  def favorites_count(node)
    content_tag :span, class: "card-favorite-count" do
      content_tag(:i, "" ,class: "icon-heart") + node.cached_votes_total
    end
  end

But that doesn't output the number value in node.cached_votes_total. It outputs everything else though, and in the correct semantic order. It is just the final part of this doesn't work quite yet.

like image 949
marcamillion Avatar asked Oct 23 '25 17:10

marcamillion


2 Answers

The last expression in the do block for a content_tag is what the content will be. So change it to:

def favorites_count(node)
  content_tag :span, class: "card-favorite-count" do
    node.cached_votes_total + content_tag(:i, class: "icon-heart")
  end
end

So you concatenate those two together. Of course, you will need to do nil checks on node.cached_total_votes now.

like image 116
tolgap Avatar answered Oct 26 '25 07:10

tolgap


So I figured out the answer. This is what the correct solution looks like:

  def favorites_count(node)
    content_tag :span, class: "card-favorite-count" do
      concat(content_tag(:i, "" ,class: "icon-heart"))
      concat(node.cached_votes_total)
    end
  end

Note that I had to use two concat() methods, because concat basically acts like a puts to the view. content_tag basically just returns the last line in the method to the view, so to override that I have to do that.

This comes from this article and this SO answer.

like image 42
marcamillion Avatar answered Oct 26 '25 09:10

marcamillion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!