Spaceless.php 2.0 KB

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