0

Can we add different classes to first row and last row of view only ?

I have created a view of products listing in which i need to add unique class only in first row and last row of view.

I need to implement it for creating different designs layout of each row. In drupal 7 i did it by using below code :

 end($rows);
$last = key($rows);
?>
<?php if (!empty($title)): ?>
<h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id == $last): ?>
<?php $classes_array[$id] .= ' last-element'; ?>
<?php endif; ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>
 </div>

How we can do the same in drupal 8?

  • Dont downvote the question without having proper reason as its not a off topic? – user52318 Aug 14 '18 at 12:42
  • You can use css to target first and last items you know? See pseudo selectors :first-child and :last-child – Beebee Aug 14 '18 at 13:00
  • we are creating dynamic section not static it might have 10 or 15 rows – user52318 Aug 14 '18 at 13:04
  • CSS doesn't care about that. – Kevin Aug 14 '18 at 13:04
  • @Vikramfz16 how is div:last-child and div:first-child different than div.first-item and div.last-item? – Beebee Aug 14 '18 at 13:05
4

You would probably be fine with just doing this with css ( see Beebee's comment on your post), but I will answer the question.

You can use loop.first and loop.last in twig. Here is an example I used to make it work in a menu.

<ul class="menu">
    {% for item in items %}
        {%
            set classes = [
            'menu-item',
            item.is_expanded ? 'menu-item--expanded',
            item.is_collapsed ? 'menu-item--collapsed',
            item.in_active_trail ? 'menu-item--active-trail',
        ]
        %}
        {% if loop.first %}
            <li {{ item.attributes.addClass('first-element') }}>
               {{ link(item.title, item.url) }}
               {% if item.below %}
                  {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
               {% endif %}
            </li>
        {% endif %}
        {% if loop.last %}
            <li{{ item.attributes.addClass('last-element') }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% else %}
            <li{{ item.attributes.addClass(classes) }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% endif %}

    {% endfor %}
</ul>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy