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

后端 未结 4 1201
萌比男神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 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
    

提交回复
热议问题