gpt4 book ai didi

html - 遍历 Rails 对象和数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:59:28 25 4
gpt4 key购买 nike

我正在迭代模型对象@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com