Solution:
Stacks should be used in layouts. There are not many reasons, if any, to put a stack in the same blade template.
In the example in the docs, the stack is defined in the layout’s <head>
. The template that extends that layout is where you would push or prepend the code to that stack. (Although the docs could be more clear about this)
The blade view’s sections are rendered and then placed into the extended layout in the appropriate places, which is what makes it possible to define where content is loaded.
You can’t define a section with yield and then define the content inside that section. As soon as the layout hits @yield or @stack, it’s going to render what has been defined in that section.
In other words, this works because the section content is rendered before it hits yield:
@section('test')
<h1>Hello World</h1>
@endsection
@yield('test')
But this won’t:
@yield('test')
@section('test')
<h1>Hello World</h1>
@endsection
The same logical order applies to stacks.