Laravel - @yield和@section之间的区别?

问题描述 投票:18回答:5

Laravel docs,您可以包括“部分”使用以下两种方法中的布局:

<html>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

由于@yield也可以通过使用@yield('section', 'Default Content')一些默认的内容,是@yield只是不使用@section一个@parent速记?

@section
    <!-- Nothing here -->
@show

有什么其他方面的差异有哪些?

laravel blade
5个回答
25
投票

这条线清除了这样的困惑:“请注意,观点延伸刀片布局简单地从布局覆盖部分布局的内容可以包括在使用中部分@parent指令子视图。”

所以,如果你已经在总体布局定义的@section,将除非您指定的子布局的@parent@section覆盖。

但对于@yield,它总是会从孩子规划的段落。这意味着它总是覆盖@yield部分,即使它定义为@yield('section', 'Default Content')默认。

我希望清除你的困惑。让我知道如果您有更多问题。谢谢


23
投票

答案很简单:除非你想要做更复杂的东西,然后提供一个默认的@yield始终使用string


龙答:无论@yield和@section ..用于@show每当你扩展刀片模板可选覆盖。你可以用@yield所做的一切,也可以用@section .. @show左右完成,但没有别的办法。这里是他们做了什么:

@yield( '主')

  • 可以通过@section(“主”).. @endsection被替换
  • 可以提供一个默认字符串,但没有HTML!默认字符串将在副刀片模板显示没有@section(“主”)..提供@endsection时。

@section( '主').. @show

  • 可以通过@section(“主”).. @endsection被替换
  • 可以提供一个默认的HTML代码。默认的HTML代码将在副刀片模板显示没有@section(“主”)设置时。
  • 可以通过@section(“主”)@父.. @endsection代替,附加地示出的缺省HTML代码。

这里是一些例子:test.blade.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
    <h1>This is a test</h1>

    @yield('mainA')
    @yield('mainB', 'This is the alternative 1')
    @yield('mainC', '<p>This is the alternative 2</p>')
    @yield('mainD', 'This is the alternative 3')

    @section('testA')
    @show

    @section('testB')
      This is the alternative 4
    @show

    @section('testC')
      <p>This is the alternative 5</p>
    @show

    @section('testD')
      <p>This is the alternative 6</p>
    @show


  </body>
</html>

这里是它扩展了其他刃文件的另一个文件名为testA.blade.php

@extends('test')

@section('mainD')
  <div>
    <p>First replacement!</p>
    <hr>
  </div>
@endsection

@section('testC')
  <div>
    <p>Second replacement!</p>
    <hr>
  </div>
@endsection

@section('testD')
  @parent
  <div>
    <p>Additional content</p>
    <hr>
  </div>
@endsection

这就是结果:

enter image description here


3
投票

基本上yield('content')是一个标记。例如,在标签,如果你把一个yield('content'),你说这部分有内容的名称和方式,你可以选择你想要的任何东西括号里面的名字。它不必是内容。它可以是产率(“内部”)。或者你想要的任何东西。

然后在你想从你的页面布局导入HTML的子页面,你刚才说section('name of the section')。 例如,如果你在你的页面布局作为yield('my_head_band') @section('my_head_band')标记你的头。

这将导入从布局页标题到您的子页面。反之亦然,在这种情况下被命名为内容的主体部分。

希望这可以帮助。


0
投票

最简单的回答:

如果你想完全覆盖在总体布局的子数据使用@yield的主人。

如果你想与@section孩子使用主机和子女数据一起使用@parent在主(或覆盖在总体布局像@yield子数据)


0
投票

刚上进行一些小的增加,@yield基本上定义一节,由overwriting数据注入,它也工作,如果我们认为@extends父视图。

现在,当我们overwrite,我们有一个新的实现完全替代的实现,就像一个公司可以决定更改/如果他们意识到出事了覆盖其全部技术。

它不应该与override混淆

© www.soinside.com 2019 - 2024. All rights reserved.