Rails中等同于Django模板的'spaceless'功能

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 %}标签等效的内容。


你尝试过使用Rails的辅助方法link_tocontent_tagcontent_for吗? - Peter Brown
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进行一些繁琐的处理。


看起来非常有前途,我会尽快试试看。 - Lloeki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接