刀片中的段和堆栈之间有什么区别?

问题描述 投票:26回答:3

我们可以使用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>
laravel templates blade
3个回答
40
投票

我可能会误会,但是区别不仅在语义上,而且在行为上也是如此。使用@ push,您可以将[多次添加到堆栈中,而(默认情况下)您可以在视图中仅填充once。在某些情况下,当您需要在模板文件中或循环中从不同位置添加内容时,这会很方便: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

追加...

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

@stack('scripts')
</head>

您可以看到,脚本堆栈将附加在example.js的script标签下。因此,您可以为每个视图推送特殊脚本。

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

6
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.