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

跟風遠走 提交于 2019-12-03 10:00:00

From the reference:

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

This initiates a new Haml engine and renders it.

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!