section.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 string
  13. */
  14. protected static $last;
  15. /**
  16. * Start injecting content into a section.
  17. *
  18. * After calling this method, the "stop" method may be used to stop injecting
  19. * content. A raw string may also be passed as the second argument, and will
  20. * cause the given string to be injected into the section directly without
  21. * using output buffering.
  22. *
  23. * <code>
  24. * // Start injecting into the "header" section
  25. * Section::start('header');
  26. *
  27. * // Inject a raw string into the "header" section
  28. * Section::start('header', '<title>Laravel</title>');
  29. * </code>
  30. *
  31. * @param string $section
  32. * @param string $content
  33. * @return void
  34. */
  35. public static function start($section, $content = '')
  36. {
  37. if ($content == '')
  38. {
  39. ob_start();
  40. static::$last = $section;
  41. }
  42. static::append($section, $content);
  43. }
  44. /**
  45. * Inject inline content into a section.
  46. *
  47. * This is helpful for injecting simple strings such as page titles.
  48. *
  49. * <code>
  50. * // Inject inline content into the "header" section
  51. * Section::inject('header', '<title>Laravel</title>');
  52. * </code>
  53. *
  54. * @param string $section
  55. * @param string $content
  56. * @return void
  57. */
  58. public static function inject($section, $content)
  59. {
  60. static::start($section, $content);
  61. }
  62. /**
  63. * Stop injecting content into a section.
  64. *
  65. * @return void
  66. */
  67. public static function stop()
  68. {
  69. static::append(static::$last, ob_get_clean());
  70. }
  71. /**
  72. * Append content to a given section.
  73. *
  74. * @param string $section
  75. * @param string $content
  76. * @return void
  77. */
  78. protected static function append($section, $content)
  79. {
  80. if (isset(static::$sections[$section]))
  81. {
  82. $content = static::$sections[$section].PHP_EOL.$content;
  83. }
  84. static::$sections[$section] = $content;
  85. }
  86. /**
  87. * Get the string contents of a section.
  88. *
  89. * @param string $section
  90. * @return string
  91. */
  92. public static function yield($section)
  93. {
  94. return (isset(static::$sections[$section])) ? static::$sections[$section] : '';
  95. }
  96. }