Personally, I don't like that much logic in the template. Even hate it. The code becomes unreadable. In such a case I would rather move all this intricate logic into the PHP part, doing some preprocessing that will result in the plain array, so the end code would be like this
<figure>
<picture>
<?php foreach ($image['srcset'] as $row): ?>
<source media="(orientation: <?=$row['orientation']?>)" type="image/<?=$row['format']?>" srcset="<?=$row['srcset'] ?>">
<?php endforeach ?>
<img src="<?=$imagePath?>lg.jpg" width="1200" height="800" alt="<?=$image['caption']?>">
</picture>
</figure>
The preprocessing PHP code should be exactly like your current code, just collecting the data into array instead of echoing it
$new = [];
foreach ($image['srcset']['ratio'] as $orientation => $ratio) {
$basePath = "assets/img/{$image['name']}/{$image['name']}-{$ratio}";
foreach($image['srcset']['format'] as $format) {
$srcset = '';
foreach($sizes as $size => $vw) {
$srcset .= $srcset ? ",":"";
$srcset .= "{$comma}{$basePath}-{$size}.{$format} {$vw}w";
}
$new[] = [
'orientation' => $orientation,
'format' => $format,
'srcset' => $srcset,
];
}
}
another possibility is to write sort of a helper function
<figure>
<picture>
<?php foreach ($image['srcset']['ratio'] as $orientation => $ratio): ?>
<?php foreach($image['srcset']['format'] as $format): ?>
<source media="(orientation: <?=$orientation?>)" type="image/<?=$format?>" srcset="<?=getsrcset($image, $ratio, $format, $key)">
<?php endforeach ?>
<? endforeach ?>
<img src="<?=$imagePath?>lg.jpg" width="1200" height="800" alt="<?=$image['caption']?>">
</picture>
</figure>
And two generic suggestions:
- short open tag is forbidden, always use
<?phpinstead of<? - do not neglect the code indentation. The proper formatting is very important, it helps to understand what does the code do