Using helpers in rails 3 to output html

后端 未结 3 1297
广开言路
广开言路 2020-12-13 04:26

I\'m trying my best to build a helper that outputs a <\'ul> consisting of all the members of a collection. For each member of the collection I want to print out a <\'

相关标签:
3条回答
  • 2020-12-13 04:58

    @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.

    0 讨论(0)
  • 2020-12-13 05:09

    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.

    0 讨论(0)
  • 2020-12-13 05:16

    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

    0 讨论(0)
提交回复
热议问题