"无空间"等同于Rails中的Django模板

Llo*_*eki 4 templates ruby-on-rails django-templates equivalent

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

<li class='aclass anotherclass <%= maybeaconditionalclass %>'>
   <a href="<%= some stuff %>">
     <%= some other stuff %>
   </a>
</li>
Run Code Online (Sandbox Code Playgroud)

不幸的是,链接内部产生尾随空格,导致拖尾下划线.现在虽然可读性较差,但我可以忍受这个:

<li class='apossibleclass anotherclass <%= maybeaconditionalclass %>'>
   <a href="<%= some stuff %>"><%= some other stuff %></a>
</li>
Run Code Online (Sandbox Code Playgroud)

如果我现在考虑这种事情,仍然存在同样的问题:

li.apossibleclass:after {
    content: "/";
}
Run Code Online (Sandbox Code Playgroud)

因为结束A和LI之间的空白阻碍了应该坚持我的列表项目结束的方式.我只能制造那种丑陋的混乱作为解决方法:

<li class='apossibleclass anotherclass <%= maybeaconditionalclass %>'>
   <a href="<%= some stuff %>"><%= some other stuff %></a></li>
Run Code Online (Sandbox Code Playgroud)

Django提出了一个很好的解决方案:{%spaceless%},所以我在寻找Rails erb模板中{%spaceless%}标签的等价物.

whi*_*ark 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
Run Code Online (Sandbox Code Playgroud)

这是你可以放在你的帮手application_helper.rb,然后像这样使用:

<%= spaceless do %>
  <p>
      <a href="foo/"> Foo </a>
  </p>
<% end %>
Run Code Online (Sandbox Code Playgroud)

...这将导致输出字符串像

<p><a href="foo/"> Foo </a></p>
Run Code Online (Sandbox Code Playgroud)

遗憾的是,这只适用于Rails 3.Rails 2支持这样的功能将需要一些脏的黑客入侵ERb.