Follow this Blog!

Aug 20, 2013

f Comment

Yii: How to Modify the Raw HTML code of the Rendered View With a Filter?

Amazon In Yii how do you modify the raw HTML code of the rendered view (including layout) with a filter? For example you would like to HTML escape or encode the resulting HTML code, or maybe you want to apply your own custom logic to modify the HTML code rendered by a view. How do you do that in Yii?

You can read the basics of filter at http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#filter even though it won't answer all your questions.
Define the filter
Let's create an object-based filter that HTML escapes only the ampersands of the rendered view. This means every instance of ampersand, or &, needs to be replaced with the corresponding HTML entity, or &. It's that simple.

First I add a PHP file called HtmlPurifier.php at protected/filters/ directory. Then I define the filter class as the following.
<?php
class HtmlPurifier extends COutputProcessor
{
 public $options=null;

 public function processOutput($output)
 {
  //$output stores the raw HTML of the entire webpage, including layout and view
  //let's transform every & that doesn't end in ; into &amp;
  $output = preg_replace('/&(?![a-zA-Z0-9#]+;)/', '&amp;', $output); // preg_replace() is global by default
  parent::processOutput($output);
 }
}
?>
The regular expression I use may seem daunting at first but it really isn't. It simply says "replace every & that does not end in ; with &amp;".

Add this filter in the controller
Suppose you'd like to apply this filter to the view rendered by the main action of your controller here's the filters() you'd define in that controller class.
public function filters() {
 return array(
  array(
   'application.filters.HtmlPurifier + main'
  ),
  // other filters you may have ...
 );
}
The path alias application.filters.HtmlPurifier specifies that the filter class file is protected/filters/HtmlPurifier.php.

If you create an object based filter it MUST be within an array in filters() function.
That's it. Try rendering a page and see if the non-HTML escaped ampersands are properly HTML escaped now.

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael