|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * @link http://www.yiiframework.com/ |
| 4 | + * @copyright Copyright (c) 2008 Yii Software LLC |
| 5 | + * @license http://www.yiiframework.com/license/ |
| 6 | + */ |
| 7 | + |
| 8 | +namespace yii\widgets; |
| 9 | + |
| 10 | +use yii\base\Widget; |
| 11 | + |
| 12 | +/** |
| 13 | + * Spaceless widget removes whitespace characters between HTML tags. Whitespaces within HTML tags |
| 14 | + * or in a plain text are always left untouched. |
| 15 | + * |
| 16 | + * Usage example: |
| 17 | + * ```php |
| 18 | + * <body> |
| 19 | + * <?php Spaceless::begin(); ?> |
| 20 | + * <div class="nav-bar"> |
| 21 | + * <!-- tags --> |
| 22 | + * </div> |
| 23 | + * <div class="content"> |
| 24 | + * <!-- tags --> |
| 25 | + * </div> |
| 26 | + * <?php Spaceless::end(); ?> |
| 27 | + * </body> |
| 28 | + * ``` |
| 29 | + * |
| 30 | + * This example will generate the following HTML: |
| 31 | + * ```html |
| 32 | + * <body> |
| 33 | + * <div class="navbar"><!-- other tags --></div><div class="content"><!-- other tags --></div></body> |
| 34 | + * ``` |
| 35 | + * |
| 36 | + * This method is not designed for content compression (you should use `gzip` output compression to |
| 37 | + * achieve it). Main intention is to strip out extra whitespace characters between HTML tags in order |
| 38 | + * to avoid browser rendering quirks in some circumstances (e.g. newlines between inline-block elements). |
| 39 | + * |
| 40 | + * Note, never use this method with `pre` or `textarea` tags. It's not that trivial to deal with such tags |
| 41 | + * as it may seem at first sight. For this case you should consider using |
| 42 | + * [HTML Tidy Project](http://tidy.sourceforge.net/) instead. |
| 43 | + * |
| 44 | + * @see http://tidy.sourceforge.net/ |
| 45 | + * @author resurtm <[email protected]> |
| 46 | + * @since 2.0 |
| 47 | + */ |
| 48 | +class Spaceless extends Widget |
| 49 | +{ |
| 50 | + /** |
| 51 | + * Starts capturing an output to be cleaned from whitespace characters between HTML tags. |
| 52 | + */ |
| 53 | + public function init() |
| 54 | + { |
| 55 | + ob_start(); |
| 56 | + ob_implicit_flush(false); |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Marks the end of content to be cleaned from whitespace characters between HTML tags. |
| 61 | + * Stops capturing an output and echoes cleaned result. |
| 62 | + */ |
| 63 | + public function run() |
| 64 | + { |
| 65 | + echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); |
| 66 | + } |
| 67 | +} |
0 commit comments