Indent your HTML code with a Smarty plugin

XHTML code

If you are using Smarty as a template system in your PHP project you will be very pleased to use this tiny-but-very-useful outputfilter that I made.

Smarty as you can read in its documentation has some extension points where you can create plugins into to extend its functionality. One of them are outputfilters, that allow us to operate on a template’s output, after the template is loaded and executed, but before the output is displayed.

So you can modify your final HTML code with those extentions point without a any pain.

The code

/**
* Output Filter for indent HTML code after sending it to the end user.
*
* @param string $output, the HTML code without proper indentation
* @return string, the HTML code with proper indentation
*/
function smarty_outputfilter_indent_html($output, &$smarty)
 {

     $config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200,
           'drop-proprietary-attributes'    =>    false,
           'indent-cdata' => true,
           'indent-spaces' => 4,
    );

    try {

        // Use tidy library to make up the HTML code
        $tidy = new tidy;
        $tidy->parseString($output, $config, 'utf8');
        $tidy->cleanRepair();

    } catch (Exception $e) {
        // If something went wrong just output the original HTML code
        $tidy = $output;
    }

    // Output the HTML code
    return $tidy;

 }

Installation

For use this plugin you must have installed in your server the tidy PHP module. If you have a Debian based server it’s quite simple. Just issue in your terminal:

 sudo apt-get install php5-tidy

and after that remember to restart the server, in my case Apache 2:

 sudo service apache2 restart

after that you can drop the file in your smarty plugins directory and register into the Smarty object.

class Template extends Smarty
{
    function __construct($theme, $filters=array())
    {
        $this->loadFilter("output","indent_html");
    }
}

This code is under the BSD license, so feel free to use it