How to Write Smarty Plugin; Example smarty Plugin – Trim

Writing smarty plugin is very easy. It is just like writing a custom function for Smarty. Only work you need to do is to name it differently. The plugin name is of the pattern:

function smarty_block_yourName($params, $content, &$smarty) {}

After creating a function like the above, just drop the file inside Plugins/ folder. Simple! is not it?

Now, you will call this block function like this:

{yourName}
Tpl content ,,…
{/yourName}

Strip function is called in the same way.

{strip}
<style>
@font-face {
  font-family: <a-remote-font-name>
  src: <source> [,<source>]*;
  [font-weight: <weight>];
  [font-style: <style>];
}
</style>
{/strip}

Output (similar to):

<style>@font-face {  font-family: <a-remote-font-name>  src: <source> [,<source>]*;  [font-weight: <weight>];  [font-style: <style>];}</style>

All whitespace has been trimmed.

The output I would like to see is this:

<style>
@font-face {
  font-family: <a-remote-font-name>
  src: <source> [,<source>]*;
  [font-weight: <weight>];
  [font-style: <style>];
}
</style>

Here is our trim block function code, which will be called the same way as strip.
Its output will be like the above I wished.

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */
/**
*  Trim extra newlines from smarty generated output
*  @output content with trimmed extra newlines
*
*/
function smarty_block_trim($params, $content, &$smarty)
{
    if (is_null($content)) {
        return;
    }
    $content = preg_replace('@[rn]{2,}@', "n", $content);
    return $content;
}
?>

The $content is passed to block function (plugin) at the 2nd call of the function ({trim}). As soon as we receive the content, we can process it and then return it back for output to screen. The content passed to the block is the processed content ready for output and not the template (tpl) code.

  • # 1 - by Satya Prakash

    Oh! I need to edit the post as this line is not correct:
    preg_replace(‘@[rn]{2,}@’, “n”, $content).
    It should be preg_replace(‘@[rn]{2,}@’, “n”, $content)

Comments are open for an year period. Please, write here on Facebook page.