Why bother with perch_layout?

If you’re new to Perch, one of the first perch functions you need to get to grips with is perch_layout();

If you’ve built anything with php you’ve probably used <?php include('somefile.php); ?> to ensure you don’t end up repeating the same chunks of code throughout your site. Or maybe, if you’ve come to perch from Wordpress, you’ve used the get_header(); and get_footer(); functions. perch_layout is similar to all these. It’s used to include common page elements.

So why bother? Why not just use include();?

perch_layout has a few big advantages: Firstly it always looks in the templates/layouts folder in your perch installation. To mimic that in php we’d have to do something like:

<?php include $_SERVER['DOCUMENT_ROOT']."/perch/templates/layouts/myfile.php";?>

Which is pretty ugly. Instead with perch_layout we can just use the following function

<?php perch_layout('myfile');?> 

Much better.

Secondly, we can pass variables to perch_layout(); so in the above example, we can pass a variable called ‘title’

perch_layout('global.header', array(
    'title'=>'Homepage',
));

And then display that variable within header.php

<title><?php perch_layout_var('title'); ?></title>

Traditionally, perch_layout is used for things like the header, sidebar and footer of a site. But it doesn’t need to be. On perchd.io for example, we’d create a folder of svg files and replaced the file extension with php. Now we can include these SVGs inline:

<?php perch_layout('icons/icon--twitter')?>

For more on perch_layout, check out the official docs »


Leave a comment