Commit 9a0717dc by Qiang Xue

Merge pull request #560 from resurtm/spaceless-widget

Add spaceless widget.
parents 6fd1c166 aa8fbd96
<?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:
*
* ```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:
*
* ```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
{
/**
* Starts capturing an output to be cleaned from whitespace characters between HTML tags.
*/
public function init()
{
ob_start();
ob_implicit_flush(false);
}
/**
* 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()));
}
}
<?php
namespace yiiunit\framework\widgets;
use yii\widgets\Spaceless;
class SpacelessTest extends \yiiunit\TestCase
{
public function testWidget()
{
ob_start();
ob_implicit_flush(false);
echo "<body>\n";
Spaceless::begin();
echo "\t<div class='wrapper'>\n";
Spaceless::begin();
echo "\t\t<div class='left-column'>\n";
echo "\t\t\t<p>This is a left bar!</p>\n";
echo "\t\t</div>\n\n";
echo "\t\t<div class='right-column'>\n";
echo "\t\t\t<p>This is a right bar!</p>\n";
echo "\t\t</div>\n";
Spaceless::end();
echo "\t</div>\n";
Spaceless::end();
echo "\t<p>Bye!</p>\n";
echo "</body>\n";
$expected="<body>\n<div class='wrapper'><div class='left-column'><p>This is a left bar!</p>".
"</div><div class='right-column'><p>This is a right bar!</p></div></div>\t<p>Bye!</p>\n</body>\n";
$this->assertEquals($expected,ob_get_clean());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment