【问题标题】:Add a class to the first child in a loop using Middleman使用中间人向循环中的第一个孩子添加一个类
【发布时间】:2015-12-13 11:26:13
【问题描述】:

我正在为我的博客创建一个滑块,我想向其中添加一组特色项目,滑块要求第一个子加载类 selected。

我该怎么做if first child do thiselse do that之类的事情

这是我目前所拥有的:

<ul class="cd-hero-slider">
    <% blog.articles.select {|a| a.data[:featured] }.each do |article| %>
      <li class="selected" style="background-image: url('https://images.unsplash.com/photo-1447014421976-7fec21d26d86?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=c82e04e1201234889daab5427f481731')">
        <div class="cd-full-width">
          <h2><%= link_to article.title, article %></h2>
          <p><%= article.summary(250) %></p>
          <%= link_to 'Read More', article, :class => 'cd-btn' %>
        </div>
      </li>
    <% end %>
  </ul>

【问题讨论】:

    标签: ruby middleman static-site


    【解决方案1】:

    使用 each_with_index 而不是 each - 这将为您提供对象以及数组中的位置,首先是 0:

    <% blog.articles.select {|a| a.data[:featured] }.each_with_index do |article, index| %>
      <% if index == 0 %>
        <li>I'm the first!</li>
      <% else %>
        <li>Not the first</li>
      <% end %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-23
      • 2015-08-09
      • 2013-09-28
      • 2021-12-09
      • 2014-08-30
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多