Is it possible to have Haml indent HTML generated by a view helper in Rails?

前提是你 提交于 2020-01-03 11:57:29

问题


Say I have a things resource with a view helper method such as:

module ThingsHelper
  def foo
    ret = ""
    3.times { ret += content_tag(:li, "foo") }
    content_tag(:ul, ret)
  end
end

This, then, is used in a template:

%p
  = foo 

The HTML source that's generated looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title>Foo</title>
    </head>
</html>
<body>
    <p>
        <ul><li>foo</li><li>foo</li><li>foo</li></ul>
    </p>
</body>

As you can see, the helper output is not indented as the rest of the code. Any way to remedy this?


回答1:


Try out the haml_tag helper method provided with Haml. It's like content_tag in some ways, but it outputs properly indented HTML. The main difference is that it outputs directly to the template, rather than returning a string. For example:

module ThingsHelper
  def foo
    haml_tag :ul do
      3.times { haml_tag(:li, "foo") }
    end
  end
end

(As a side note, it's considered very bad Ruby style to use something other than two spaces for indentation).




回答2:


I doubt it - at least not without a significant amount of mucking around.

Your = foo is simply printing what is returned by your foo helper - it's not getting parsed by haml. And you can't write haml in your helper method either.

The simplest way I can think of to deal with this is to just add literal whitespace characters in your helper (ie \n and \t).

You could also require the relevant haml class(es) in your helper and call the parsing methods manually on ret, but this is probably more complicated than worthwhile.



来源:https://stackoverflow.com/questions/1528166/is-it-possible-to-have-haml-indent-html-generated-by-a-view-helper-in-rails

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