Hi,
How can I combine a simple loop like that:
<?php $n = 0; foreach($page->children()->offset(0) as $subpage): $n++; ?>
with:
<?php if($subpage->myField()->isTrue()): ?>
In other words, I want to make a loop with only subpage items who have a field with a “true” key.
Thanks!
fvsch
2
Not sure what doesn’t work with what you wrote:
<?php $n = 0; foreach($page->children()->offset(0) as $subpage): $n++; ?>
<?php if($subpage->myField()->isTrue()): ?>
<?= $subpage->title() ?><br>
<?php endif; ?>
<?php endforeach; ?>
Is the problem that the $n
value does not match the number of pages you’re listing?
Why do you use a counter in the first place?
In any case, it might be better to filter the pages collection before iterating, like this:
<?php
$subpages = $page->children()->filter(function($p){
return $p->myField()->isTrue();
});
?>
<?php foreach($subpages as $subpage): ?>
<?= $subpage->title() ?><br>
<?php endforeach; ?>
You could define the $subpages
in a controller instead of inside the template, if you want to keep things a bit separated.
Thanks, I just didn’t though about combining the two functions!