4

请注意以下内容的可读性和平衡性:

<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 %}标记的等价物。

4

1 回答 1

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 支持这样的功能需要对 ERb 进行一些肮脏的修改。

于 2011-08-03T11:07:16.477 回答