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.
02 | class HtmlPurifier extends COutputProcessor |
06 | public function processOutput($output) |
10 | $output = preg_replace( '/&(?![a-zA-Z0-9#]+;)/' , '&' , $output); |
11 | 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 &".
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.
1 | public function filters() { |
4 | 'application.filters.HtmlPurifier + main' |
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!