Foreach subpages with different template

Hi there,

I’m trying to build a blog scenario where I would like to display each subpage (depending on it’s template) with a different layout and not really sure how to do it.

For example template1 will be posts with only images, template2 video, template3 text.


$template1 = ; // Get subpages with template 1
$template2 = ; // Get subpages with template 2
$template3 = ; // Get subpages with template 3

foreach($page->children()->flip() as $subpage): ?>

    <?php if($template1) : ?>
        <div class="template1">
            // template1 stuff
    <?php endif; ?>

    <?php if($template2) : ?>
        <div class="template2">
            // template2 stuff
    <?php endif; ?>

    <?php if($template3) : ?>
        <div class="template3">
            // template3 stuff
    <?php endif; ?>

<?php endforeach; ?>

I’d suggest to use snippets for each different template, then you don’t need all the if statements and can call the snippets via the intended template.

Let’s assume your video posts are created with a blueprint video-post.yml, your image posts with image-post.yml etc., then create the following snippets:

  • video-post.php
  • image-post.php
  • etc.

Then call them in your template:

<?php foreach($page->children()->flip() as $subpage): ?>
<?php snippet($subpage->intendedTemplate()); ?>
<?php endforeach ?> 

Other options for creating different types of posts include using the modules or the page-builder plugin. However, using snippets is perfectly fine and you don’t rely on plugins.

Somehow I missed the existence of intendedTemplate()
Works like a charm! Thank you

But then what’s the logic when echo content in the snippets? <?php echo $page->title() ?> doesn’t fetch anything.

Then pass the page on to the snippet:

<?php snippet($subpage->intendedTemplate(), ['page' => $subpage]); ?>
1 Like