加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – “无空间”等效于Rails中的Django模板

发布时间:2020-12-17 02:41:57 所属栏目:百科 来源:网络整理
导读:请注意以下内容的可读性和平衡性: li class='aclass anotherclass %= maybeaconditionalclass %' a href="%= some stuff %" %= some other stuff % /a/li 不幸的是,链接内部产生尾随空格,导致拖尾下划线.现在虽然可读性较差,但我可以忍受这个: li class='a
请注意以下内容的可读性和平衡性:

<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中没有类似的东西.所以我编写了它.

# 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读