【问题标题】:Add dynamic property to content_tag将动态属性添加到 content_tag
【发布时间】:2014-02-28 15:51:18
【问题描述】:

这似乎是一个非常简单的问题。假设我想动态检查条件以便在某些Helper Module 中为某些标签添加一些属性:

def add_tag(hash)
    content_tag(:div, class: "some_class", rows: "#{check_rows(hash)}")
end

def check_rows(hash)
    hash[:rows].nil? ? "" : hash[:rows]
end

这很好用,但如果hash[:rows].nil?,我不想让rows 出现在生成的标签内。所以我尝试了这个

content_tag(:div, class: "some_class", "#{check_rows(hash)}")

   def check_rows(hash)
    hash[:rows].nil? ? "" : ":rows =>  hash[:rows]"
   end

"#{check_rows(hash)}" 无法识别。有没有办法做到这一点?

【问题讨论】:

  • '"#{check_rows(hash)}" 无法识别'是什么意思?

标签: ruby-on-rails ruby tags


【解决方案1】:

我认为你对 content_tag 方法的论点是错误的。试试这个:

def add_tag(hash)
    content_tag(:div, check_rows(hash), class: "some_class")
end

【讨论】:

    【解决方案2】:

    替换

    def add_tag(hash)
        content_tag(:div, class: "some_class", rows: "#{check_rows(hash)}")
    end
    
    def check_rows(hash)
        hash[:rows].nil? ? "" : hash[:rows]
    end
    

    def add_tag(hash)
       content_tag(:div, "#{check_rows(hash)}", class: "some_class")
    end
    
    def check_rows(hash)
       hash[:rows].nil? ? "" : {"rows" =>  hash[:rows]}
    end
    

    无法识别的原因是您将 :rows => hash[:rows] 作为字符串传递,而 content_tag 需要哈希。

    【讨论】:

    • 还要显示html内容吗?
    猜你喜欢
    • 2015-06-22
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多