使用单行循环在 Rails 视图中生成 HTML 类

Using single-line looping to generate HTML classes in a Rails view

我有一个哈希格式:

@meals = [
        {
            name: 'Roasted Chicken A La Ratatouille',
            description: '',
            tags: ['chicken'],
            type: ['program'],
            image_url: ''
        },
        {
            name: 'Turkey Nuggets with Buffalo Cauliflower & Spinach',
            description: '',
            tags: ['turkey'],
            type: ['program', 'veggies'],
            image_url: ''
        }
     ]

并且我希望能够将餐点 type 解包为元素的 class 名称:

<% meals.shuffle.each do |meal| %>

  <!-- Line in question --> 
  <div class="item col-3 p-2 a b <%= meal[:type].each {|t| t } %>">
  <!-- End line in question --> 

    <div class="card">
      <img class="card-img-top" src="<%= meal[:image_url] %>">
      <div class="card-body">
        <h5 class="card-title font-medium"><%= meal[:name] %></h5>
      </div>
      <div class="card-footer text-muted justify-content-center row">
        <% meal[:tags].each do |tag| %>
          <span style="margin: 2px;" class="badge bg-info-gradiant pointer"><%= tag %></span>
        <% end -%>
      </div>
    </div>
  </div>
<% end %>

但是当视图呈现时,它显示为:

<div class="item col-3 p-2 a b ["program"]" style="position: absolute; left: 295px; top: 0px;">
    <div class="card" style="height: 399px;">
        ...
    </div>
</div>

程序显示在括号内的位置。是否有不同的方法来完成此操作,以便将数组中的值应用为 class 名称?

您可以使用 Array#join 将 classes 的数组显式转换为 space 分隔的 class 名称的字符串:

<div class="item col-3 p-2 a b <%= meal[:type].join(' ') %>">

工作原理:

> meal[:type]
=> ["program", "veggies"]
> meal[:type].join(' ')
=> "program veggies"

请注意,meal[:type].each 并不像您想象的那样。它为 meal[:type] 数组中的每个元素调用该块,并期望该块执行副作用(例如记录某些内容或保存某些内容),然后它 returns 未修改的 meal[:type] 数组.如果你想得到一个新数组,你必须使用 Array#map 代替:

> meal[:type].each { |t| t.reverse }
=> ["program", "veggies"] # the block doesn’t affect the return value
> meal[:type].map { |t| t.reverse }
=> ["margorp", "seiggev"] # the block affects each returned element