Using helpers in rails 3 to output html

这一生的挚爱 提交于 2019-11-28 17:14:45
Dave Pirotte

I agree with the comment above recommending the use of a partial... but if you DID need to do this in a helper, this is a cleaner way to implement:

def display_all(collection)
  content_tag(:ul, class: "list") do
    collection.collect do |member|
      concat(content_tag(:li, id: member.name.gsub(' ', '-').downcase.strip) do
        member.name
      end)
    end
  end
end

I'd pass in a collection explicitly rather than passing in a symbol to create a collection so you aren't always required to display ALL the records in a particular table at once. You could add pagination, etc.

Linh Chau

@Joe, You can still use your method display_all(collection_sym) Just use: return html.html_safe instead of: return html

I still find that in many situations, it is better to generate HTML from helpers, instead of using partials. So the html_safe function in Rails 3 will make sure that you generate HTML, instead of converting it to String.

As @TheDelChop says, you need a concat for the inner content_tag, otherwise the output is just <ul></ul>

Here's what that looks like:

def display_all(collection)
  content_tag(:ul, :class => "list") do
    collection.collect do |member|
      concat(
        content_tag(:li, :id => member.name.gsub(' ', '-').downcase.strip) do
          member.name
        end
      )
    end
  end
end

More explanation here: Nesting content_tag in Rails 3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!