简体   繁体   中英

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

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 scratch 2) I have to use that verbose syntax like content_tag or haml_tag.

I know that it's possible to define partials with HAML systax that will serve as helper. Though 1) as for me it's inconvinient to create a separate file for each small tiny function 2) invocation syntax for partial is quite verbose.

Ideally i'd like my *_helper class to look like this:

- def some_helper(*its_args)
  .some_class
    = some_ruby_expression
  %some_tag#some_id
    - another_expression do
      etc

or at least like this:

define_haml_helper :some_helper, [:arg1, :arg2], %{
  .some_class
    = some_ruby_expression
  %some_tag#some_id
    - another_expression do
      etc
}

Is there a plugin that solves my issue?

Alternatively, maybe you can describe how do you refactor HAML snippets to reusable elements (helpers/functions/partials/builders/etc)?

From the reference :

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

This initiates a new Haml engine and renders it.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM