Creating custom expression modifiers

PHPTAL comes with some basic expression modifiers (not:, exists:, string:, php:, path:).

These modifiers are defined by ZPT specifications but PHPTALES can be extended with your own modifiers to manipulate strings, date, money numbers, objects, whatever…

The aim of a modifier is to return some PHP code that will be included in the template PHP source.

Modifiers are used at parse time. If you change the behavior of a modifier, you'll have to delete generated PHP files and reparse all templates using it.

Please note that modifiers produce code, and mustn't echo data!

Any PHP function starting with "phptal_tales_" is usable as a modifier.

Modifiers takes two arguments:

For example, in the following TAL template,

<span tal:replace="some-modifier: my/path/value"/>

The src argument will be "my/path/value", and the $nothrow boolean will be false, because tal:replace requires the path to be fully resolvable.

An expression like:

<span tal:replace="some-modifier: my/path/value | other/path"/>

Will use 2 modifiers:

Remember, path: is the implicit modifier used when no other modifier is specified.

Modifiers can use other modifiers to generate simpler PHP code. The example below shows this.

//
// This modifier will return a money formated string (XXX.XX)
//
// usage:
//
//      money: path/to/my/amount
//
// this modifier uses phptal_tales() function to generate the
// PHP code that will return the value of the modifier argument.
//
// in the example:
//
//      money: path/to/my/amount
//
// the produced code will be something looking like:
//
//      sprintf("%01.2f", phptal_path($ctx->path, "to/my/amount"))
//
// This code will be included right into the template where needed.
//
// @param string $src
//      The expression string
// @param string $nothrow
//      A boolean indicating if exceptions may be throw by phptal_path if
//      the path does not exists.
// @return string
//      PHP code to include in the template
//
function phptal_tales_money( $src, $nothrow )
{
    // remove spaces we do not require here
    $src = trim($src);
    return 'sprintf("%01.2f", '.phptal_tales($src, $nothrow).')';
}