A global block

Perch Blocks allow you (and the content editors) to build flexible pages. Your whole master page can be:

perch_layout('global.top');

perch_content_create('Blocks', ['template' => 'blocks.html']);
perch_content('Blocks');

perch_layout('global.bottom');

On some projects, I find it useful to give the editor the ability to add some global sections (e.g. a featured listing of existing items or a contact form) via blocks so they can place it wherever they want on the page (if they want to include it at all). The content can come from anywhere; a Collection, a Content Region or an add-on like Perch Blog and Perch Shop. To acheive this, I use Layout includes.

Create a single block for your global sections:

<perch:block type="global" label="Global Section" icon="world">
    <!--* TODO *-->
</perch:block>

Add a select field and add the suppress attribute so it does not output anything:

<perch:block type="global" label="Global Section" icon="world">
    <perch:content id="file" type="select" label="Include Section" options="" suppress>
</perch:block>

For each option, create a layout and use the layout’s relative path as the option’s value. So if you create the layout templates/layouts/latest_posts, your option would be Latest Posts|latest_posts:

<perch:block type="global" label="Global Section" icon="world">
    <perch:content id="file" type="select" label="Include Section" options="Latest Posts|latest_posts,Featured Products|featured_products,Contact Form|contact_form" suppress>
</perch:block>

Inside these layouts you can output anything you want and call any Perch runtime function such as perch_collection() and perch_content().

Add a Perch layout include:

<perch:block type="global" label="Global Section" icon="world">
    <perch:content id="file" type="select" label="Include Section" options="Latest Posts|latest_posts,Featured Products|featured_products,Contact Form|contact_form" suppress>
    <perch:layout path="<perch:content id="file">">
</perch:block>

Now if the editor selects the Featured Products option, the templates/layouts/featured_products.php will be used (and the same applies to the other options):

<perch:layout path="featured_products">

One thing I also tend to pass to the layouts is the block unique ID _block_id which I may use to dynamically target elements in Javascript:

<perch:layout path="<perch:content id="path">" block="<perch:content id="_block_id" type="hidden">">

The block attribute here becomes a layout variable. So you can access it inside a layout with perch_layout_var():

$blockID = perch_layout_var('block');
link

Related articles