Blade中的Section和Stack有什么区别? [英] What is the difference between Section and Stack in Blade?

查看:182
本文介绍了Blade中的Section和Stack有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

那为什么要有栈呢? https://laravel.com/docs/5.2/blade#stacks

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>

推荐答案

我可能会误会,但是区别不仅在语义上,而且在行为上也是如此. 使用 @push ,您可以追加到堆栈中所需的次数,而(默认情况下)您可以仅一次填充 @section . 在某些情况下,当您需要跨模板文件或循环添加来自不同位置的内容时,这会派上用场:

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:

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

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>

这篇关于Blade中的Section和Stack有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆