Add property to collection elements

I may be misunderstanding Kirby data structure, but I want to add a property to all images in a collection within a controller then access those in the template. This doesn’t work because of the image object structure: how could I achieve this?

Controller code

$positions = array('left', 'middle', 'right'); 
foreach($section->images() as $image) {
    $index = $section->indexOf($image);
    $image['position'] = $positions[$index % 3]; 
}

Template code

 <img class='<?= $image->position() ?>' />

First of all, something seems wrong in how you calculate your index. Assuming that $section is a page, you cannot call indexOf(), because that method is a collection method and not a page method.

Secondly, to assign a value to an element, you can use the map() method:

$positions = array('left', 'middle', 'right'); 
$images = $section->images()->map(function($file) use($positions) {
    $index = $file->siblings()->indexOf($file);
    $file->position =  $positions[$index % 3];
    return $file;
});

foreach($images as $image): ?>
 <img src="<?= $image->url() ?>" class="<?= $image->position() ?>">
<?php endforeach ?>