If Parent uses Template "foo" or if Parent is Home

I’m writing conditional statements to render different content on the same template.
I’d like to show different data if the page is a subpage of a certain page template foo.

<?php if ($page->parent()->template('foo')) : ?>
  <?php foreach…
<h3> a list of things when it is a grandchild…</h3>
<?php else : ?>
 <?php foreach…
<h3> a list of things when it is a child…</h3>
<?php endif ?>

I’ve searched and checked out the filter and filterBy pages, but not finding a solution yet.

Should I just be checking to see if the URL contains /foo/?

Or maybe I should be checking to see if the parent is Home, else…

Solved it using the second method (check if parent is Home, by checking if page has a Parent count of more than 0).

After reading this:

<?php if ($page->parents()->count() > 0) : ?>

I decided to check using that method (if page has parent count greater than 0). This works, but I’d still love a better method. I like that it works, but I fear it’s using incorrect logic and would break if the site structure would grow beyond this.

Let me know what you think I should use instead.

how about you pack that logic of querying the parent template in a page model? the code is still the same though. that would a least make your frontend code more readable.

1 Like

An alternative would be to use snippets without an if-statement, with snippets that use the name of the parent template (or a string that contains the parent template):

<?php foreach ($page->children() as $child) {
  snippet($page->parent()->template()->name(), ['child' => $child]);
}
1 Like

Okay, so, to add in another option, Bruno also suggested the isDescendantOf():

…that way I can check to see if it is a descendant of that section, and move forward:

<?php if ($page->isDescendantOf('foo')) : ?>

This seems to get me what I needed. Thank you both!