Add a class to the first element of foreach loop

Hello,

I’m trying to add a class to the first element of an image loop but it doesn’t work.
Here is my code:

	<?php
	$items = $page->images();
	$first = $items->first();
	?>
	<?php foreach($page->images() as $image): ?>
		<img <?php if($item == $first) echo ' class="active"' ?> class="slide" src="<?= $image->url() ?>">
	<?php endforeach ?>

Thank you in advance for your help :slight_smile:

does not tell us much. Please be more specific about what you expect and what actually happen.

Beside of this, I guess you will have two class attributes on you first item, because your class="slide" might appear everywhere, including the first item.

Just saw, that your $item variable seems not to be defined, at least not in this code snippet.

Again, help could be provided better if we would now what really happens or not.

<?php $items = $page->images(); ?>
<?php foreach($items as $image): ?>
    <img class="slide<?= $items->indexOf($image) === 0 ? ' active' : '' ?>" src="<?= $image->url() ?>">
<?php endforeach ?>
1 Like

Hey thanks for your reply.
I need to have the class slide on all my elements and add the active class only on the first element. I found this to help me: https://getkirby.com/docs/cookbook/templating/loops#first-and-last-items.
But if I try to reproduce this, my page shows the error message from Kirby.

Thank you for your help.
I tried but my page shows kirby error message :frowning:

What error message?

This message

The code I posted is correct, though.

Must be some other issue.

Please enable debugging in your config.php

'debug' => true

Okay debug mode tells me this: “syntax error, unexpected ‘’ active ‘’ (T_CONSTANT_ENCAPSED_STRING), expecting ‘,’ or ‘;’”

You are missing a question mark before the string ' active'

1 Like

It works :smiley:
Thank you both very much for your precious help