作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我正在迭代模型对象@products(目前在数据库中有 3 个),但我还需要对 View 中返回的每个对象应用不同的样式。
这是我在 page_controller.rb 中的当前代码,用于仅获取前 3 个产品:
@products = Product.where(id: 1..3)
在我看来index.html.erb:
<div class="row pricing-table">
<% @products.each do |p| %>
<div class="col-md-4">
<div class="panel <%= custom-style %>">
<div class="panel-heading"><h3 class="text-center"><%= p.title %></h3></div>
<div class="panel-body text-center">
<p class="lead" style="font-size:40px"><strong><%= number_to_currency(p.price, precision: 0) %>/month</strong></p>
</div>
<ul class="list-group list-group-flush text-center list-no-bullets">
<%= p.description.html_safe %>
</ul>
<div class="panel-footer">
<%= link_to("Request Quote", "/quote_forms/new", class: "btn btn-lg btn-block btn-danger-override") %>
</div>
</div>
</div>
<% end %>
</div>
现在,我要做的是将自定义样式添加到第 4 行 div
元素。 (我已经加入了 erb 语法,所以你可以看到我在说什么)
因此,我向 page_controller.rb 添加了一组 CSS 样式类:
@style = ["danger", "info", "success"]
希望有办法让第 4 行 div
元素成为:
<div class="panel panel-danger">
在第一次迭代中,然后在第二次迭代中:
<div class="panel panel-info">
等等。
我怎样才能做到这一点?
最佳答案
使用each_with_index
遍历产品,然后使用索引获取对应的样式名称:
<div class="row pricing-table">
<% @products.each_with_index do |p, p_index| %>
<div class="col-md-4">
<div class='panel <%= "panel-#{@style[p_index % @style.size]}" %>'>
<div class="panel-heading"><h3 class="text-center"><%= p.title %></h3></div>
<div class="panel-body text-center">
<p class="lead" style="font-size:40px"><strong><%= number_to_currency(p.price, precision: 0) %>/month</strong></p>
</div>
<ul class="list-group list-group-flush text-center list-no-bullets">
<%= p.description.html_safe %>
</ul>
<div class="panel-footer">
<%= link_to("Request Quote", "/quote_forms/new", class: "btn btn-lg btn-block btn-danger-override") %>
</div>
</div>
</div>
<% end %>
</div>
关于html - 遍历 Rails 对象和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29976098/
我是一名优秀的程序员,十分优秀!