Manually Loading a Filter

There’s also another way to load filters into Smarty, and that is the usual way of creating separate plug-in files, and storing them into a predefined directory. Smarty will then include the given filter plug-in file, and use it when needed.

Continuing with the standard format of the register_*filter functions, the filter plug-in filename should conform to these rules:

Type

String to use in plug-in filename

Prefilters

prefilter

Postfilters

postfilter

Output filters

outputfilter

For instance, if you would like to create an output filter plug-in called append_benchmark_data, then the filename should be outputfilter.append_benchmark_data.php. If the same plug-in were supposed to be a prefilter one, then the filename would be prefilter.append_benchmark_data.php, and so on. This filter plug-in file should be saved under Smarty’s plugin sub-directory.

The same rules apply for the function name to be placed within the plug-in file. For our first example above of an output filter plug-in called append_benchmark_data, we would need to create the following PHP script:

<?php
function smarty_outputfilter_append_benchmark_data($source, &$smarty)
{
    global $benchmark;

    $source .= ‘<div id=”benchmark”>’;
    $source .= ‘Generated in ‘ . $benchmark . ‘ secs.’;
    $source .= ‘</div>’;

    return $source;
}
?>

The plug-in above will append some extra HTML to the generated output from a template, and will return that modified output, referenced above in the $source variable.

Now that we have the plug-in file created correctly, we still need to tell Smarty that we want it to use this filter when processing templates. Since this is a manual process, you will use the load_filter Smarty method to do this, as shown next:

<?php
include_once(‘libs/Smarty.class.php’);
$smarty = new Smarty;

$smarty->load_filter(‘output’, ‘append_benchmark_data’);

$smarty->display(‘templates/example1.tpl’);
?>

The first parameter to the load_filter method is the filter type (possible values are pre, post, and output). This method will tell Smarty that we want it to use this plug-in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.190.167