Spaceless.php 1.95 KB
Newer Older
resurtm committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\widgets;

use yii\base\Widget;

/**
 * Spaceless widget removes whitespace characters between HTML tags. Whitespaces within HTML tags
 * or in a plain text are always left untouched.
 *
 * Usage example:
17
 *
resurtm committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31
 * ```php
 * <body>
 *     <?php Spaceless::begin(); ?>
 *         <div class="nav-bar">
 *             <!-- tags -->
 *         </div>
 *         <div class="content">
 *             <!-- tags -->
 *         </div>
 *     <?php Spaceless::end(); ?>
 * </body>
 * ```
 *
 * This example will generate the following HTML:
32
 *
resurtm committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
 * ```html
 * <body>
 *     <div class="navbar"><!-- other tags --></div><div class="content"><!-- other tags --></div></body>
 * ```
 *
 * This method is not designed for content compression (you should use `gzip` output compression to
 * achieve it). Main intention is to strip out extra whitespace characters between HTML tags in order
 * to avoid browser rendering quirks in some circumstances (e.g. newlines between inline-block elements).
 *
 * Note, never use this method with `pre` or `textarea` tags. It's not that trivial to deal with such tags
 * as it may seem at first sight. For this case you should consider using
 * [HTML Tidy Project](http://tidy.sourceforge.net/) instead.
 *
 * @see http://tidy.sourceforge.net/
 * @author resurtm <resurtm@gmail.com>
 * @since 2.0
 */
class Spaceless extends Widget
{
52 53 54 55 56 57 58 59
    /**
     * Starts capturing an output to be cleaned from whitespace characters between HTML tags.
     */
    public function init()
    {
        ob_start();
        ob_implicit_flush(false);
    }
resurtm committed
60

61 62 63 64 65 66 67 68
    /**
     * Marks the end of content to be cleaned from whitespace characters between HTML tags.
     * Stops capturing an output and echoes cleaned result.
     */
    public function run()
    {
        echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
    }
resurtm committed
69
}