Passing variables into templates

The PerchSystem class can be used to set variables at runtime which are then available within templates.

Note, this only works for templates which are parsed at runtime – such as content rendered with perch_content_custom() rather than the precompiled output from perch_content().

Using PerchSystem::set_var('name', 'value') you can do things like this:

<?php
    PerchSystem::set_var('lang', 'en');
    perch_content_custom('My region', array(
        'template'=>'template.html'
    ));
?>

Then in your template:

<a href="/<perch:content id="lang" />/contact/">Contact Us</a>

The variable set with set_var() is passed into the template and merged with the regular content. You should think about avoiding ID collisions, and perhaps devise a naming scheme.

Bulk setting variables

You can also use the plural PerchSystem::set_vars() to set multiple variables at once. It takes a PHP associative array with keys and values.

<?php
    PerchSystem::set_vars(array(
        'colour'=>'red',
        'fruit'=>'apple',
        'season'=>'winter'
    ));
?>

Unsetting variables

Variables set will persist for the duration of the page load. They can be reset by using the same name again, or explicitly unset.

PerchSystem::unset_var('lang');

Getting values back

A variable previously set can be read back.

$lang = PerchSystem::get_var('lang');

Or all get be fetched at once, as an associative array.

print_r(PerchSystem::get_vars());