How to get page titles in Perch runway collection, blog or basic page

Simple way to use one global layout file to get meta info for page titles

In my global header layout file I use


<?php
if (perch_layout_has('blog-post')) {
      perch_blog_post_meta(perch_get('s'));
    } elseif (perch_layout_has('collection-post')) {
      echo '<title>' . perch_layout_var('title', true) . '</title>';
    }
    else{
      echo '<title>' . perch_pages_title(true) . '</title>';
    }
?>

In a collection post page, I use


<?php
$article = perch_collection('Articles', [
  'template'=>'articles/article_item.html',
  'skip-template' => true,
  'filter'   => 'slug',
  'match'    => 'eq',
  'value'    => perch_get('s'),
  ]);

  $postTitle = $article[0]['_title'];

  perch_layout('header', array(
    'collection-post' => true,
    'body_class' => 'post',
    'title' => $postTitle
  ));
?>

In a blog post page, I use


<?php
$post = perch_blog_post(perch_get('s'), true);
    if (!$post) header('Location: /errors/404');
    $title = perch_blog_post_field(perch_get('s'), 'postTitle', true);
  
  perch_layout('header', array(
    'blog-post' => true,
    'body_class' => 'post'
));
?>

In a regular page, I use


<?php
$title = perch_pages_title(true);

  perch_layout('header', [
    'body_class' => 'regular-page',
    'title' => $title . ' | scottgruber.me'
  ]);
?>

To assign the body class if its available, I use


<?php
if (perch_layout_has('body_class')) {
	echo '<body class="'.perch_layout_var('body_class', true).'">';
}else{
	echo '<body>';
}
?>

Iā€™m sure I could do more to tidy it. Not sure if the body class naming is needed or if there is a better way to do so. But so far its working pretty good.

Published on by Scott Gruber