Creating a Dynamic Post Listing

Now that we have a couple of posts in the content/posts/ directory, let’s use this data in our templates.

In home.php, we delete all static content in the “recent-posts” section and replace it with a snippet:

<section id="recent-posts">
  <?php snippet("recent-posts") ?>
</section>

Let’s create this snippet in site/snippets/recent-posts.php and bring the list view to life, step by step. First, we need to collect all post items that we want to list in a variable:

// Get all child pages in the "posts" page
$allPosts = $pages->get('posts')->children()->visible();

We ask the global $pages object for the page named “posts” and request all of its child pages that are visible (i.e. numbered).
However, we want all but the newest item (because we display this separately at the top of the homepage in special markup).

// we want all but the latest item
$recentPosts = $allPosts->flip()->slice(1);

“flipping” the collected pages will sort them newest to oldest; and using the slice() function, we remove the first object (the newest one) from the set.

We can then simply cycle through the items and output what we want to display:

<?php foreach($recentPosts as $recentPost): ?>

<article class="teaser--recent">
  <div class="meta">
    <?php echo date("M d, Y", $recentPost->date()) ?> by 
    <?php echo $recentPost->author() ?>
  </div>
  <h2><?php echo $recentPost->title() ?></h2>
  <p class="teaser-content">
    <?php echo $recentPost->text()->kirbytext()->excerpt(150) ?>
  </p>
  <p class="continue-reading">
    <a href="<?php echo $recentPost->url() ?>">Continue Reading</a>
  </p>
</article>

<?php endforeach; ?>

Code on GitHub

As implied, the very latest post is displayed a bit differently: we show a large teaser image just below its title. Here’s how this works:

<div class="teaser-image">
  <img src="<?php echo $newestPost->image('teaser.jpg')->url() ?>" />
</div>

With a page object’s image() method, you can search for a file in that page’s folder. Since we have placed a “teaser.jpg” image in the “05-chevron” folder, we can easily get hold of it. Using the url() method on the resulting image object allows us to feed this into a good old <img> tag.

You can find the complete code for the newest-post.php snippet in the corresponding commit.

Giveaways. Cheat Sheets. eBooks. Discounts.
And great content from our blog!

About Us

As the makers of Tower, the best Git client for Mac and Windows, we help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Ebay get the most out of Git.

Just like with Tower, our mission with this platform is to help people become better professionals.

That's why we provide our guides, videos, and cheat sheets (about version control with Git and lots of other topics) for free.