可以在Rails中使视图助手生成的Haml缩进HTML吗? [英] Is it possible to have Haml indent HTML generated by a view helper in Rails?
问题描述
说我有一个东西资源,它带有视图助手方法,例如:
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
然后将其用于模板:
%p
= foo
生成的HTML源代码如下:
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?
推荐答案
尝试 haml_tag
帮助器方法.在某些方面类似于content_tag
,但是它输出正确缩进的HTML.主要区别在于它直接输出到模板,而不是返回字符串.例如:
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
(作为一个附带说明,使用两个空格以外的其他字符进行缩进被认为是非常糟糕的Ruby风格.)
(As a side note, it's considered very bad Ruby style to use something other than two spaces for indentation).
这篇关于可以在Rails中使视图助手生成的Haml缩进HTML吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!