What is the difference between Section and Stack in Blade?

让人想犯罪 __ 提交于 2019-12-31 11:42:38

问题


We can use a section to define some HTML and then yield that somewhere else.

So why do we have stacks? https://laravel.com/docs/5.2/blade#stacks

It's doing exactly the same thing with different keywords, but has fewer options (No inheritance).

@push('scripts')
    <script src="/example.js"></script>
@endpush

<head>
    <!-- Head Contents -->

    @stack('scripts')
</head>

Can be done with section:

@section('scripts')
    <script src="/example.js"></script>
@endsection

<head>
    <!-- Head Contents -->

    @yield('scripts')
</head>

回答1:


I might be mistaken, but the difference is not only semantically, but in behaviour as well. With @push you append as many times as needed to a stack, while (by default) you may fill @section only once in your views. In some situations this comes in handy when you need to add content from different locations across your template files or in loops:

index.blade.php:

@extends('master')

...  

@for ($i = 0; $i < 3; $i++)

  @push('test-push')
    <script type="text/javascript">
    // Push {{ $i }}
    </script>
  @endpush

  @section('test-section')
    <script type="text/javascript">
    // Section {{ $i }}
    </script>
  @endsection

@endfor

master.blade.php

    @stack('test-push')
    @yield('test-section')
</body>

result:

    <script type="text/javascript">
    // Push 0
    </script>
        <script type="text/javascript">
    // Push 1
    </script>
        <script type="text/javascript">
    // Push 2
    </script>
    <script type="text/javascript">
    // Section 0
    </script>
    </body>



回答2:


Stack is someway appropriate for scripts , with stack you can Append as much as you need .

@push('scripts')
    <script src="/example.js"></script>
 @endpush

Append …

<head>
<!-- Head Contents -->

@stack('scripts')
</head>

As you can see the scripts stack will be appended under the script tag of example.js . So you can push special scripts for each view .



来源:https://stackoverflow.com/questions/35672485/what-is-the-difference-between-section-and-stack-in-blade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!