Custom Modifiers

Custom Modifiers are subclasses of patTemplate_Modifier and have to be placed inside patTemplate/Modifier. The filename has to match the last part of the classname. That means if you would like to create a filter that truncates sentences you will have to create a new class 'patTemplate_Modifier_Truncate' and place it into patTemplate/Modifier/Truncate.php.

The class has to implement one method modify( string value, array params ) that has to return the modified value. You may do whatever you like inside this method to modify the value.

patTemplate will pass two parameters to your method:

    * string $value, the value of the variable
    * array $params, an associative array containing all attributes of the var tag except the ones, that are used internally (name, default, copyFrom, modifier)


The truncate modifier could look like this:

01        <?PHP
02        /**
03        * patTemplate modfifier Truncate
04        *
05        * $Id: modifiers.xml,v 1.1 2004/05/11 19:46:09 schst Exp $
06        *
07        * @package        patTemplate
08        * @subpackage     Modifiers
09        * @author        Stephan Schmidt <schst@php.net>
10        */
11        class patTemplate_Modifier_Truncate extends patTemplate_Modifier
12        {
13           /**
14            * truncate the string
15            *
16            * @access    public
17            * @param    string        value
18            * @return    string       modified value
19            */
20            function modify( $value, $params = array() )
21            {
22                /**
23                 * no length specified
24                 */
25                if( !isset( $params['length'] ) )
26                    return $value;
27       
28                /**
29                 * is shorter than the length
30                 */
31                if( $params['length'] >strlen( $value ) )
32                    return $value;
33       
34                return substr( $value, 0, $params['length'] ) . '...';
35            }
36        }
37        ?>


If you copy this file to the Modifier folder, you may instantly use it in your template files, by specifying it in the modifier attribute of any <patTemplate:var/> tag.

01    <patTemplate:tmpl name="page">
02          <div>
03                <patTemplate:var name="myVar" modifier="Truncate" length="50"/>
04          </div>
05    </patTemplate:tmpl>


If you now pass a value that is longer than 50 chars, the modifier will automatically truncate it, before inserting it into the template.