Rails: Is it possible to write view helpers with HAML syntax?

后端 未结 4 1202
萌比男神i
萌比男神i 2021-02-12 19:05

During refactoring it would be quite handy just to copy part of HAML template and paste it to helper\'s code. Currently in such cases 1) I have to rewrite that part of view from

相关标签:
4条回答
  • 2021-02-12 19:53

    Haml now has a capture_haml method that you can use to accomplish this.

      def some_helper
        capture_haml do
          .some_class
            = yield
          #some-code-after
        end
      end
    
    some_helper do
      %h1 Hello World
    end
    => <div class="some_class">
         <h1>Hello World</h1>
       </div>
       <div id="some-code-after"></div>
    

    Here is a link with more info on capture_haml: http://haml.info/docs/yardoc/Haml/Helpers.html#capture_haml-instance_method

    0 讨论(0)
  • 2021-02-12 19:56

    From the reference:

    def render_haml(code)
        engine = Haml::Engine.new(code)
        engine.render
    end
    

    This initiates a new Haml engine and renders it.

    0 讨论(0)
  • 2021-02-12 20:02

    I used heredoc for such purposes:

      def view_helper
        Haml::Engine.new(<<~HAML).render
          .example
            #id ID
            .desc Description
        HAML
      end
    

    This way has a lot of issues with a scope of variables, so, as mentioned above, the much more correct way is to use partials for this.

    UPD1: here is a solution on how to solve issues with scope:

      def view_helper
        Haml::Engine.new(<<~HAML).render(self)
          .form
            = form_tag root_path do
              = submit_tag :submit
        HAML
      end
    

    UPD2: even better solution(founded on the internet):

    def render_haml(haml, locals = {})
      Haml::Engine.new(haml.strip_heredoc, format: :html5).render(self, locals)
    end
    
    def greeting
      render_haml <<-HAML
        .greeting
          Welcome to
          %span.greeting--location
            = Rails.env
      HAML
    end
    
    0 讨论(0)
  • 2021-02-12 20:04

    If all you are after is a method for small reusable snippets, how about partials with local variables? http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

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