Rails / ERB中的条件标签包装

编程入门 行业动态 更新时间:2024-10-07 12:26:58
本文介绍了Rails / ERB中的条件标签包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

用ERB编写此代码最容易理解和/或简洁的方法是什么?最好不要编写自己的方法,因为我想将更清洁的解决方案传播给公司中的其他人。

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 %>

==更新==

I

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 %>

推荐答案

如果您真的希望DIV是有条件的,则可以做这样的事情:

If you really want the DIV to be conditional, you could do something like this:

将其放入application_helper.rb

put this in application_helper.rb

def conditional_div(options={}, &block) if options.delete(:show_div) concat content_tag(:div, capture(&block), options) else concat capture(&block) end end

那么您可以在自己的视图中这样使用:

which then you can use like this in your view:

<% @items.each do |item| %> <% conditional_div(:show_div => item.isolated?, :class => 'isolated') do %> <%= item.name.pluralize %> <% end %> <% end %>

更多推荐

Rails / ERB中的条件标签包装

本文发布于:2023-11-30 12:40:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   标签   Rails   ERB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!