Rails view helpers in helper file

后端 未结 3 2199
星月不相逢
星月不相逢 2020-12-13 20:27

I\'m probably missing something obvious here but here\'s what I\'m trying to do.

From the view, I\'m calling a custom helper function

相关标签:
3条回答
  • 2020-12-13 21:06

    As it turns out, I had to do something like this

    def display_services
      html = "<div>"
      html << (form_for @user do |f|
       f.text_field ...
      end)
      html << "</div>"
    end
    

    Note the () wrapped around the form block. If someone has a better solution, let me know.

    0 讨论(0)
  • 2020-12-13 21:11

    IMHO, you should not have HTML hardcoded in Ruby code. Instead, prefer partials views.

    module ServicesHelper
      def display_services(user)
        render :partial => "shared/display_services", :locals => {:user => user}
      end
    end
    
    0 讨论(0)
  • 2020-12-13 21:20

    Just a suggestion for style, I like doing something like this:

    In your view:

    <% display_services %>
    

    Please note that the = isn't needed any more. The helper then uses concat() to append something to your page and the putting-long-strings-together thing is obsolete too:

    def display_services
      concat("<div>")
      form_for @user do |f|
        f.text_field ...
      end
      concat("</div>")
    end
    

    Is it nessaccary to put the <div> tag into the helper. If you need a helper for embedding something into a block you could use some yield-magic as well:

    def block_helper
      concat("<div>")
      yield
      concat("</div>")
    end
    

    And use it like this in your view - of course with helpers too:

    <% block_helper do %>
      cool block<br/>
      <% display_services %>
    <% end %>
    
    0 讨论(0)
提交回复
热议问题