Smarty pre-, post- and outputfilters

This article presumes that you understand how Saurus CMS Extensions and Smarty plugins work, if not then refer to http://www.smarty.net/manual/en/plugins.php.

Smarty has 3 different filters:

  1. Prefilter is activated before the template is compiled into PHP.
  2. Postfilter is activated after the template is compiled into PHP, but before the compiled code is saved and used.
  3. Outputfilter is activated each time the template is called and operates on the HTML output of the template.

Pre- and postfilters are only activated during template compilation, that is when you makes changes to the template or clear the template cache. Outputfilters are used every time a template is viewed except when CMS site cache is turned on. Outputfilters can't be used with CMS site cache functionality since the cache stores the direct HTML output of a page and essentially turns the page into static HTML so Smarty is not used at all and therefore no filters are applied.

Setting path of the plugins folder

To use Smarty filters with CMS use your extension's extension.config.php file. In extension.config.php you can define a path to your custom Smarty plugins like:

$EXTENSION['smarty_plugins'] = '/path/to/your/plugins/folder';

 

Example from default extension Saurus4:

$EXTENSION['smarty_plugins'] = '../../../extensions/'.$EXTENSION['name'].'/smarty_plugins';

 

When using the relative path keep in mind that for Smarty the path starts inside the folder "/classes/smarty/" not in the website root folder.

Setting filters

To define which filters are used on which templates use the $EXTENSION['smarty_filters'] array.
The array structure is:

template_id =>
pre => name_of_filter1, name_of_filter2 ...
post => name_of_filter1, name_of_filter2 ...
output => name_of_filter1, name_of_filter2 ...
...

If you use a string 'all' instead of template ID then those filters are used on all site templates.

Example

$EXTENSION['smarty_filters'] = array(
 'all' => array(
  'pre' => array('strip_custom_comments', ),
  'post' => array('add_compile_timestamp', ),
 ),
 1056 => array(
  'output' => array('word_highlighter', 'email_obfuscator', ),
 ),
 1083 => array(
  'output' => array('content_strtoupper', ),
 ),
);

This filter definition tells CMS to run on all templates a prefilter named “strip_custom_comments” and a postfilter named “add_compile_timestamp”. On template which has an ID of 1056 are run two outputfilters named “word_highlighter” and “email_obfuscator” and on template with a ID of 1082 an outputfilter named “content_strtoupper”.

Example of a outputfilter “content_strtoupper”

Insert following PHP code into the file "outputfilter.content_strtoupper.php" in your smarty plugins folder.

function smarty_outputfilter_content_strtoupper($source, &$smarty)
{
return strtoupper($source);
}