Rails / ERB 中的条件标签包装
在 ERB 中最易读和/或最简洁的方式是什么?编写我自己的方法并不可取,因为我想向公司中的其他人传播一个更干净的解决方案。
<% @items.each do |item| %>
<% if item.isolated? %>
<div class="isolated">
<% end %>
<%= item.name.pluralize %> <%# you can't win with indentation %>
<% if item.isolated? %>
</div>
<% end %>
<% end %>
==更新==
我使用了Gal答案的更通用版本,即与标签无关。
def conditional_wrapper(condition=true, options={}, &block)
options[:tag] ||= :div
if condition == true
concat content_tag(options[:tag], capture(&block), options.delete_if{|k,v| k == :tag})
else
concat capture(&block)
end
end
== 用法
<% @items.each do |item| %>
<% conditional_wrapper(item.isolated?, :class => "isolated") do %>
<%= item.name.pluralize %>
<% end %>
<% end %>
What would be the most readable and/or concise way to write this in ERB? Writing my own method isn't preferable, as I would like to spread a cleaner solution for this to others in my company.
<% @items.each do |item| %>
<% if item.isolated? %>
<div class="isolated">
<% end %>
<%= item.name.pluralize %> <%# you can't win with indentation %>
<% if item.isolated? %>
</div>
<% end %>
<% end %>
== Update ==
I used a more generic version of Gal's answer that is tag agnostic.
def conditional_wrapper(condition=true, options={}, &block)
options[:tag] ||= :div
if condition == true
concat content_tag(options[:tag], capture(&block), options.delete_if{|k,v| k == :tag})
else
concat capture(&block)
end
end
== Usage
<% @items.each do |item| %>
<% conditional_wrapper(item.isolated?, :class => "isolated") do %>
<%= item.name.pluralize %>
<% end %>
<% end %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您确实希望 DIV 有条件,您可以执行以下操作:
将其放入 application_helper.rb 中
,然后您可以在视图中像这样使用:
If you really want the DIV to be conditional, you could do something like this:
put this in application_helper.rb
which then you can use like this in your view:
尝试:
Try:
我喜欢 PreciousBodilyFluids 的答案,但它并不严格按照您现有的方法执行的操作。如果你真的不能有一个包装 div,这可能是更好的选择:
完成所有这些的辅助方法可能如下所示:
然后你的视图代码将如下所示:
I like PreciousBodilyFluids' answer, but it doesn't strictly do exactly what your existing method does. If you really cannot have a wrapping div, this may be prefereable:
A helper method to do all of this would probably look like this:
Then your view code would look like this: