選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Spaceless.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. ob_start();
  55. ob_implicit_flush(false);
  56. }
  57. /**
  58. * Marks the end of content to be cleaned from whitespace characters between HTML tags.
  59. * Stops capturing an output and echoes cleaned result.
  60. */
  61. public function run()
  62. {
  63. echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
  64. }
  65. }