Filter child pages by template not working

Hey folks,

Running into an issue right now where I’m trying to do two different foreach on child pages, depending on which template that page is using, however, for some reason, that’s not working.

Here’s what I got…

<?php foreach($page->children()->filterBy('template', 'act_ballroom') as $act) { ?>
<h1>FOUND ONE</h1>
<?php } ?>

This solution doesn’t bring up anything. However, if I try…

<?php foreach($page->children() as $act) { ?>
<h1>FOUND ONE</h1>
<?php } ?>

…I do get a hit. I’m 100% certain the page has a template of act_ballroom, so I’m not sure where I’m going wrong here.

Thanks in advance.

And immediately after posting that I figured out the solution. I’ll write it here in case Googling led you here.

the filterBy('template) function is defined by what template the page will end up as, and not what kind of blueprint you used to make it. So, if you have the content file as act_ballroom.txt, but you haven’t yet build a act_ballroom.php template in your templates folder, this will come through as default and therefore your filter won’t work as intended.

TLDR: Make sure you have a template matching your blueprint to use filterBy(template)

2 Likes

What about:

<?php foreach($page->children() as $act) {
if($act->template() == 'act_ballroom') { ?>
<h1>FOUND ONE</h1>
<?php } else { ?>
// do something else
<?php } ?>

Your finding is correct. However, any Page also have the intendedTemplate() method to cover cases like yours. So this should work:

<?php foreach($page->children()->filterBy('intendedTemplate', 'act_ballroom') as $act) : ?>
    <h1><?php echo $act->title()->html() ?></h1>
<?php endforeach ?>
4 Likes

Oooh! That’s great to learn. Thanks, @pedroborges