You are here: WikiStart/Docs/Advanced/Modifiers


Using variable modifiers

Variable modifiers allow the template designer to modify the values that have been passed from PHP before they will be displayed to the browser.

Imagine the following PHP script:

<?php
$tmpl = new patTemplate();
$tmpl->setRoot('templates');
$tmpl->readTemplatesFromInput('modifier.tmpl');
$tmpl->addVar( 'page', 'multiline', 'This contains
some
line
breaks...' );
$tmpl->addVar( 'page', 'birthday', '1974-05-12' );

$tmpl->displayParsedTemplate();
?>

The business-logic adds two values to the template, but both of them are quite problematic:

  • The multiline variable contains linebreaks, which are not visible in HTML
  • The birthday variable probably does not have the preferred format.

Both problems can be solved in the template alone:

<patTemplate:tmpl name="page">
  Apply a modifier to multiline:
  <patTemplate:var name="multiline" modifier="nl2br" modifierType="php"/>

  Dateformat modfifier:<br />
  <patTemplate:var name="birthday" modifier="dateformat" format="%d.%m.%Y"/>
</patTemplate:tmpl>

There are two ways variable modifiers can be used:

  • You can specify any PHP function that accepts a string as its sole parameter and also returns a value. The returned value will be used as the value in the template.
  • You may use any of the provided modifiers that ship with the patTemplate distribution. Take a look at the patTemplate/Modifier directory to see, which modifiers we provide.

If none of the modifiers included in the dsitribution solves your problem, you can easily write a new modifier.

Using more than one modifier

Since version 3.1.0a2 it is also possible to use more than one modifier per variable, by specifying a list of comma-separated functions.

Using the short-modifiers syntax

If you are familiar with the Smarty templating engine, you might prefer their syntax to specify a variable modfifier. patTemplate provides an input filter, that allows you to use the same syntax. It can easily be enabled:

$tmpl = new patTemplate();
$tmpl->applyInputFilter('ShortModifiers');

You can be specify the variable modifiers in the following fashion:

<patTemplate:tmpl name="page">
  Apply a modifier to multiline:
  {MULTILINE|nl2br}

  Dateformat modfifier:<br />
  {BIRTHDAY|Dateformat|format:%d.%m.%Y}
</patTemplate:tmpl>