rails, How to build table in helper using content_tag?

后端 未结 5 1338
广开言路
广开言路 2020-12-23 22:38

I defined function in application helper:

def display_standard_table(columns, collection = {})    
  content_tag :table do      
    concat content_tag :thea         


        
相关标签:
5条回答
  • 2020-12-23 23:06

    Actually you are only missing a plus between content tags, you can find a similar question here

    Rails- nested content_tag

    The problem with this, is that maybe you will get a syntax error because of the way you are using the blocks, if you use a "{}" instead of "do end" statements you are going to be Ok.

    Here (Change to the way the block is handled) you can find an example and a workaround in the case you use Rails 3 because apparently Rails 3 ignore the result of the collect statement when is inside of the content tag.

    0 讨论(0)
  • 2020-12-23 23:19
    def display_standard_table(columns, collection = {})
    
     thead = content_tag :thead do
       content_tag :tr do
        columns.collect {|column|  concat content_tag(:th,column[:display_name])}.join().html_safe
       end
     end
    
     tbody = content_tag :tbody do
      collection.collect { |elem|
        content_tag :tr do
          columns.collect { |column|
              concat content_tag(:td, elem.attributes[column[:name]])
          }.to_s.html_safe
        end
    
      }.join().html_safe
     end
    
     content_tag :table, thead.concat(tbody)
    
    end
    
    0 讨论(0)
  • 2020-12-23 23:21

    Adding '.join().html_safe' to the end of each collect section. That's what worked for me.

      collection.collect { |elem| 
        concat content_tag(:tr, columns.collect { |column|
          content_tag(:td, elem.attributes[column[:name]])
      })
    }.join().html_safe
    
    0 讨论(0)
  • 2020-12-23 23:23

    It's the missing concat in your :tr related content_tag.

    Update

    As for the escaping, take a look at the api docs for content_tag. You need to specify not to escape it. Of course, you'd be responsible for escaping the stuff inside the tags that you want escaped in that case.

    0 讨论(0)
  • 2020-12-23 23:26

    See the railscast about that : http://railscasts.com/episodes/208-erb-blocks-in-rails-3 all is explain how you manage your block helper in rails 3

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