【问题标题】:Why does this nested content_tag not render properly?为什么这个嵌套的 content_tag 不能正确呈现?
【发布时间】:2015-10-08 13:40:44
【问题描述】:

我的助手中有这个:

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

在视图中是这样调用的:

<%= favorites_count(node) %>

这就呈现了:

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

如何让它渲染整个东西?

编辑 1

根据@tolgap 下面的建议,我尝试了这个:

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

但这不会输出node.cached_votes_total 中的数值。它会输出其他所有内容,并以正确的语义顺序输出。这只是最后一部分还没有完全奏效。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 helpers


    【解决方案1】:

    所以我想出了答案。正确的解决方案如下所示:

      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
    

    请注意,我必须使用两个 concat() 方法,因为 concat 基本上就像视图的放置一样。 content_tag 基本上只是将方法中的最后一行返回给视图,所以要覆盖它,我必须这样做。

    这来自this article 和这个SO answer

    【讨论】:

      【解决方案2】:

      do 块中 content_tag 的最后一个表达式是内容。所以改成:

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

      所以你将这两者连接在一起。当然,您现在需要对node.cached_total_votes 进行nil 检查。

      【讨论】:

      • 我收到了这个错误:ActiveSupport::SafeBuffer can't be coerced into Fixnumnode.cached_votes_total... 行。
      • 好的...我交换了它们。即我做了content_tag(:i, " ", class: "icon-heart") + node.cached_votes_total。问题是现在我看到了心脏,但是我没有看到来自node.cached_votes_total 的内容。在 HTML 中,它打印为 ""
      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 2021-01-29
      • 2017-08-03
      • 2012-12-22
      相关资源
      最近更新 更多