Perch Templates: Not Only for Front-end

Perch has a templating language that is often used to render HTML to be displayed on the front-end of your site. That’s not all you can use it for. If you build Perch add-ons, you can make use of the templating engine wherever you need it.

I’ve recently built a Perch app that retrieves some data from the database, renders some HTML using the data then converts the HTML to a PDF document. Initially I approached this in PHP. Here’s a simplified example of what I used:

$html .= '<!doctype html><html><head><style>';

    $html .= '
        * {
            font-family: "Helvetica", "Arial", sans-serif;

        /* more styling */

    $html .= '</style></head><body>';
    $html .= '<table class="table">';

        $html .= '<tr>';
            $html .= '<th>Some heading</th>';
            $html .= '<td>'.$heading.'</td>';
        $html .= '</tr>';

        $html .= '<tr>';
            $html .= '<th>Date</th>';
            $html .= '<td>'.$HTML->encode(strftime('%d %b %Y | %H:%M', strtotime($date)).'</td>';
        $html .= '</tr>';

        foreach($fields as $label => $details) {
            $html .= '<tr>';
                $html .= '<th>'.$HTML->encode($label).'</th>';
                $html .= '<td>'.$HTML->encode($details).'</td>';
            $html .= '</tr>';
    $html .= '</table>';
$html .= '</body></html>';

There’s nothing wrong with this. It works, but I much rather maintain the HTML in a HTML file. So I used Perch’s template engine to render the HTML.

I’ve discussed using Perch API for rendering templates in the post titled Template API.

$data = [
    'heading' => $heading,
    'date' => $date,
    'fields' => $fields,

$Template = $API->get('Template');
$Template->set('pdf/export.html', 'content');
$html = $Template->render($data);

And the template is all in HTML (and Perch tags):

<!doctype html>

        * {
            font-family: "Helvetica", "Arial", sans-serif;

        /* more syling */

    <table class="table">
            <td><perch:content id="heading"></td>

            <td><perch:content id="date" format="%d %b %Y | %H:%M"></td>

        <perch:repeater id="fields">
                <th><perch:content id="label"></th>
                <td><perch:content id="value"></td>


If you’ve read the post Template API, the concept of rendering templates is not new to you. The approach discussed above is another application of the Perch API to help you build Perch apps. The templating language is not limited to rendering HTML for front-end only. It’s a templating language that you can use. It’s up to you to decide how you use it.


Related articles