Blade 中的 Section 和 Stack 有什么区别?

What is the difference between Section and Stack in Blade?

我们可以使用 section 定义一些 HTML,然后在其他地方定义 yield

那么为什么我们有堆栈? https://laravel.com/docs/5.2/blade#stacks

它使用不同的关键字做完全相同的事情,但选项较少(无继承)。

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

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

    @stack('scripts')
</head>

可以通过以下部分完成:

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

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

    @yield('scripts')
</head>

我可能错了,但区别不仅在语义上,而且在行为上也是如此。 使用 @pushappend 根据需要多次添加到堆栈,而(默认情况下)你可以填充 @section 只有 一次 在您的视图中。 在某些情况下,当您需要跨模板文件或循环添加来自不同位置的内容时,这会派上用场:

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>

结果:

    <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>

堆栈在某种程度上适合脚本,有了堆栈,您可以根据需要追加。

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

追加……

<script>
@stack('scripts')
</script>

如您所见,脚本的堆栈将附加在示例 js 的脚本标签下。因此,您可以为每个视图推送特殊脚本。

@section - You can add your js css once.
@stack   - Push js css into stack (page) many times.