2016-02-27 115 views
15

我们可以使用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> 

回答

23

我也可能错了,但不同的是,不仅语义,但在行为上也是如此。 随着@push追加多次需要一个堆栈,而(默认),你可能在你的意见填写@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> 
+2

'@ section @ append'怎么样?我相信他们有同样的行为。 – Fortael

2

堆栈是某种方式适当的F或脚本,随着堆栈,你可以追加尽可能多的,你需要的。

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

追加...

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

@stack('scripts') 
</head> 

正如你可以看到脚本栈example.js的脚本标签下将追加。所以你可以为每个视图推送特殊的脚本。