html - 迭代rails中的引导选项卡内容
问题描述
我正在尝试在我的 rails 应用程序中使用引导程序创建选项卡内容。我当前的实现看起来像这样
<div class="tab-content" id="v-pills-tabContent">
<div class="tab-pane fade show active" id="v-pills-England" role="tabpanel" aria-labelledby="v-pills-England-tab">
<% @teams.each do | team | %>
<% if team.team_country == "England" %>
<div class="form-check">
<input class="form-check-input" type="radio" name="team" id="<%= team.id %>" value="<%= team.id %>">
<label class="form-check-label" for="<%= team.id %>">
<%= team.short_name %>
</label>
</div>
<% end %>
<% end %>
</div>
<div class="tab-pane fade" id="v-pills-France" role="tabpanel" aria-labelledby="v-pills-France-tab">
<% @teams.each do | team | %>
<% if team.team_country == "France"%>
<div class="form-check">
<input class="form-check-input" type="radio" name="team" id="<%= team.id %>" value="<%= team.id %>">
<label class="form-check-label" for="<%= team.id %>">
<%= team.short_name %>
</label>
</div>
<% end %>
<% end %>
</div>
</div>
这很有效,我在正确的国家得到了预期的“团队”。问题是,代码是如此重复,我正在寻找一种让它更“干”的方法。当我尝试迭代“标签内容”类时,我没有让团队在正确的国家下。这是我试过的
<div class="tab-content" id="v-pills-tabContent">
<% @teams.each do | team | %>
<div class="tab-pane fade show active" id="v-pills-<%= team.team_country %>" role="tabpanel" aria-labelledby="v-pills-<%= team.team_country %>-tab">
<%= team.short_name %>
</div>
<% end %>
</div>
什么是迭代选项卡内容并动态插入值的最佳方法,同时在正确的国家/地区拥有团队。
解决方案
一种选择是将group_by
您的数组分组到国家/地区,然后遍历这些组:
<div class="tab-content" id="v-pills-tabContent">
<% @teams.group_by(&:team_country).each do |country, country_teams| %>
<div class="tab-pane fade show active" id="v-pills-<%= country %>" role="tabpanel" aria-labelledby="v-pills-<%= country %>-tab">
<% country_teams.each do | team | %>
<div class="form-check">
<input class="form-check-input" type="radio" name="team" id="<%= team.id %>" value="<%= team.id %>">
<label class="form-check-label" for="<%= team.id %>">
<%= team.short_name %>
</label>
</div>
<% end %>
</div>
<% end %>
</div>
推荐阅读
- django - 注册后创建用户个人资料
- rest - Express Rest API 服务器(后端)具有多种注册/登录技术。你如何保持用户不被复制和登录?
- python - 试图将 WORKING python 程序转换为 C++ 但不起作用?
- c# - 反编译源码中的\uE0001.\uE000是什么意思?
- apache-spark - 在主节点中创建 Spark Session
- matlab - 成对观察的箱线图
- google-app-engine - 如何修复 put() 与 Cloud Datastore ndb 模型(Google App Engine)的冲突
- spring-boot - 我们可以仅通过 Spring Boot 将 Redis 集群与主节点连接吗
- django - 我可以直接在 HTML 文件的顶层使用 Django 模板语言,即不带或标签吗?例子 -
- wireshark - 如何使用 tshark 从 .pcapng 文件中读取接口名称?