Perch documentation

Displaying content with Perch Before and Perch After

Two really useful template tags are perch:before and perch:after. To demonstrate how these are used we’ll have a look at another area of our sidebar – the downloads module.

Our about page has a sidebar area for downloads and the mark-up for this area sensibly has marked up the list of downloads as a list. We could just copy out the li and use Perch content tags for the file and title, leaving the heading and opening and closing list tags on our page. However, if we do this they will be on the page even if we have no list items. Which is not ideal.

perch:before and perch:after solve this problem. They enable you to copy the whole block of mark-up including the heading and opening list tags into the template, only the list item will repeat – the mark-up inside perch:before will then display before the repeated region and the mark-up inside perch:after will display afterwards. If not content is added they won’t display at all. Let’s see this in practice.

Copy the entire downloads module mark-up and content to your clipboard and paste it into a new file named downloads.html saved into perch/templates/content

Inside the href of the link to the file download add a perch content tag for a file upload

<perch:content id="file" type="file" label="File" order="2" />

Then as the text of the link add a text perch content tag:

<perch:content id="title" type="text" required="true" title="true" order="1" label="Title" />

The order attribute I am using in these tags dictates what order the fields appear in the admin, this can be helpful in making the editing experience easier with fields displayed in a logical order.

This gives us our repeating li, however at the moment the entire template would repeat. This is where our before and after tags come in.

Wrap everything above the opening <li> with <perch:before></perch:before>

Then wrap everything below the closing with <perch:after></perch:after>

Save this template.

Back in about/index.php delete the entire downloads module and replace it with a perch region.

<?php perch_content('Downloads Module'); ?>

Reload the page in your browser. Then go back to admin and reload to see the new Region.

Click on this region and select the new Downloads template. Set this to allow multiples. Before adding any content go back to your page. As no content has been added nothing is being displayed, as perch before and after will only display the top and bottom of the region if at least 1 item is added.

Go back to admin and add a couple of downloads to the region.

Now return to your page to see the result.