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

时间:2019-01-17 12:47:31

标签: ruby-on-rails erb

我的哈希格式为:

@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拆开作为元素的类名称:

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

程序显示在方括号内。有没有其他方法可以做到这一点,以便将数组中的值用作类名?

1 个答案:

答案 0 :(得分:2)

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

<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]数组中的每个元素调用该块,并期望该块产生副作用(例如,记录某些内容或保存某些内容),然后返回未修改的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