请注意:
的可读性和平衡性<li class='aclass anotherclass <%= maybeaconditionalclass %>'>
<a href="<%= some stuff %>">
<%= some other stuff %>
</a>
</li>
,遗憾的是在链接中产生尾随空格,导致拖尾下划线。现在虽然可读性较差,但我可以忍受这个:
<li class='apossibleclass anotherclass <%= maybeaconditionalclass %>'>
<a href="<%= some stuff %>"><%= some other stuff %></a>
</li>
如果我现在考虑这种事情,同样的问题仍然存在:
li.apossibleclass:after {
content: "/";
}
因为结束A和LI之间的空白阻碍了我的列表项目的结束。我只能将这种丑陋的混乱作为一种解决方法:
<li class='apossibleclass anotherclass <%= maybeaconditionalclass %>'>
<a href="<%= some stuff %>"><%= some other stuff %></a></li>
Django提出了一个很好的解决方案:{% spaceless %},所以我在Rails erb模板中寻找等效的{% spaceless %}标签。
答案 0 :(得分:7)
是的,这将是一个有用的功能,据我所知,在Rails中没有类似的东西。所以我编写了它。
# Strip all whitespace between the HTML tags in the passed block, and
# on its start and end.
def spaceless(&block)
contents = capture(&block)
# Note that string returned by +capture+ is implicitly HTML-safe,
# and this mangling does not introduce unsafe changes, so I'm just
# resetting the flag.
contents.strip.gsub(/>\s+</, '><').html_safe
end
这是你可以放在application_helper.rb
中的助手,然后像这样使用:
<%= spaceless do %>
<p>
<a href="foo/"> Foo </a>
</p>
<% end %>
...这将导致输出字符串如
<p><a href="foo/"> Foo </a></p>
可悲的是,这只适用于Rails 3. Rails 2支持这样的功能需要一些脏的黑客攻击。