section.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php namespace Laravel;
  2. class Section {
  3. /**
  4. * All of the captured sections.
  5. *
  6. * @var array
  7. */
  8. public static $sections = array();
  9. /**
  10. * The last section on which injection was started.
  11. *
  12. * @var array
  13. */
  14. protected static $last = array();
  15. /**
  16. * Start injecting content into a section.
  17. *
  18. * <code>
  19. * // Start injecting into the "header" section
  20. * Section::start('header');
  21. *
  22. * // Inject a raw string into the "header" section without buffering
  23. * Section::start('header', '<title>Laravel</title>');
  24. * </code>
  25. *
  26. * @param string $section
  27. * @param string|Closure $content
  28. * @return void
  29. */
  30. public static function start($section, $content = '')
  31. {
  32. if ($content === '') ob_start() and static::$last[] = $section;
  33. static::append($section, $content);
  34. }
  35. /**
  36. * Inject inline content into a section.
  37. *
  38. * This is helpful for injecting simple strings such as page titles.
  39. *
  40. * <code>
  41. * // Inject inline content into the "header" section
  42. * Section::inject('header', '<title>Laravel</title>');
  43. * </code>
  44. *
  45. * @param string $section
  46. * @param string $content
  47. * @return void
  48. */
  49. public static function inject($section, $content)
  50. {
  51. static::start($section, $content);
  52. }
  53. /**
  54. * Stop injecting content into a section.
  55. *
  56. * @return void
  57. */
  58. public static function stop()
  59. {
  60. static::append(array_pop(static::$last), ob_get_clean());
  61. }
  62. /**
  63. * Append content to a given section.
  64. *
  65. * @param string $section
  66. * @param string $content
  67. * @return void
  68. */
  69. protected static function append($section, $content)
  70. {
  71. if (isset(static::$sections[$section]))
  72. {
  73. $content = static::$sections[$section].PHP_EOL.$content;
  74. }
  75. static::$sections[$section] = $content;
  76. }
  77. /**
  78. * Get the string contents of a section.
  79. *
  80. * @param string $section
  81. * @return string
  82. */
  83. public static function yield($section)
  84. {
  85. return (isset(static::$sections[$section])) ? static::$sections[$section] : '';
  86. }
  87. }