【问题标题】:What is the difference between Section and Stack in Blade?Blade 中的 Section 和 Stack 有什么区别?
【发布时间】:2016-06-10 21:28:01
【问题描述】:

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


    【解决方案1】:

    我可能弄错了,但区别不仅在语义上,而且在行为上。 使用 @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>
    

    【讨论】:

    • @section@append 怎么样?我相信他们有同样的行为。
    • 谢谢,不知道you may fill @section only once in your views。这导致了超级一个奇怪的错误,切换到@stack,它现在可以正常工作了
    • @fgilio 很高兴它仍然有帮助:)
    【解决方案2】:

    堆栈在某种程度上适用于脚本,您可以根据需要添加堆栈。

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

    追加……

    <head>
    <!-- Head Contents -->
    
    @stack('scripts')
    </head>
    

    如您所见,脚本堆栈将附加在 example.js 的 script 标签下。所以你可以为每个视图推送特殊的脚本。

    【讨论】:

    • 如果你只是在子视图中编写了要被删除的js,为什么要推动该代码在主视图中呈现?我不完全了解该实用程序...
    【解决方案3】:
    @section - You can add your js css once.
    @stack   - Push js css into stack (page) many times.
    

    【讨论】:

    • 不鼓励仅使用代码的答案。请解释您的答案为何以及如何解决问题。
    猜你喜欢
    • 2011-10-19
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2017-04-05
    相关资源
    最近更新 更多