Display title only if content exists

Hello, I have a question about a very common pattern but I still haven’t managed to figure it out.
I have an Events page in which I’m filtering the current events so the template looks like this:

<h1>Current Events</h1>
<?php
    $events = page('events')->events()->toStructure()->filter(function($child) {
    return $child->date(null, 'startdate') < time() && $child->date(null, 'enddate') > time();
    });
    foreach($events as $event): ?>
        <div class="event">
        …
        </div>
 <?php endforeach ?>

But if there is no current event, the title “Current Events” is still being displayed obviously. How can I solve that ? I guess I should test $child somehow… If someone could point me in the right direction that would be nice :slight_smile:

Cheers,
Daniel

Define the events first and then check if there are any:

<?php
$events = page('events')->events()->toStructure()->filter(function($child) {
    return $child->date(null, 'startdate') < time() && $child->date(null, 'enddate') > time();
});
?>
<?php if($events->count()): ?>
    <h1>Current Events</h1>
    <?php foreach($events as $event): ?>
        <div class="event">
        …
        </div>
     <?php endforeach ?>
<?php endif ?>

Maybe add an else statement before the endif saying that there are no events if there are no events…

Wonderful ! Thank you texnixe, I didn’t know about the count()function. That goes directly into my personal cookbook :slight_smile:
Have a sweet evening,
Daniel

Bookmark the Cheat Sheet, it is full of methods you will need over and over again.

Have a nice evening as well :slightly_smiling_face:

1 Like