【问题标题】:Laravel @section and @show ignoring default content - why?Laravel @section 和 @show 忽略默认内容 - 为什么?
【发布时间】:2017-08-07 21:59:59
【问题描述】:

在长时间使用更简单的系统(主要是 WP 和原始 PHP)之后,我正在学习如何为 Laravel 编写代码。为此,我正在运行最新版本并在此处遵循 Laravel 5 的教程:

https://tutorials.kode-blog.com/laravel-blade-template

但是,我遇到了一个问题。我在 Extending the Master Layout 部分,它要求您在 /resources/views/page.blade.php 上创建一个包含以下内容的文件:

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')

<p>This is appended to the master sidebar.</p>
@endsection

@section('content')
    <p>This is my body content.</p>
@endsection

位于/resources/views/layouts/master.blade.php 的主布局包含以下内容:

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

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

根据教程,路由后访问http://localhost/larashop/public/blade的结果应该是以下几行:

This is the master sidebar.

This is appended to the master sidebar.

This is my body content.

但是,我却得到:

This is appended to the master sidebar.

This is my body content.

由于某种原因,该代码忽略了代码的This is the master sidebar. 部分,或者将其替换为@section('sidebar') 中的内容。我要补充一点,否则代码处理得很好——主模板中的&lt;p&gt;&lt;/p&gt;&lt;div&gt;&lt;/div&gt; 出现在它们应该出现的位置。这只是侧边栏的默认内容没有。如果我将@show 替换为@yield('sidebar'),它确实会正确显示,但我真的很好奇这里发生了什么,如果由于某种原因我做错了什么。

我认为可能存在版本差异,因为本教程适用于 5.0,而我使用的是 5.4,但我找不到任何可以指出更改内容和原因的内容,我想在搬家之前了解这一点因为我担心我会发现更多类似的问题。

我已经发现了教程和我的安装之间的区别,即/app/Http/routes.php/routes/web.php,但是很容易找到关于它的信息。对于这个我找不到任何东西,所以有人可以帮助我吗?

【问题讨论】:

    标签: php laravel laravel-5.4


    【解决方案1】:

    在你的 page.blade.php

    .
    应该是 @yield('sidebar') 而不是 @section('sidebar')

    【讨论】:

    • 您愿意详细说明一下吗? @section('content') 工作正常,我不明白为什么我们要使用 @endsection 而不打开部分。教程错了吗?
    • 这可能是教程中的一个小错误,因为我看不到一个人如何在没有@endsection 的情况下使用@section('content')。请访问 link 获取有关 laravel 的优秀教程。另请查看 laravel 5.4 刀片文档link
    • 找出问题所在。它在 page.blade.php 上,但唯一的问题是该部分缺少 @parent。感谢您的链接,我在其中找到了答案:D
    【解决方案2】:

    刚刚找到答案。我不知道这是因为 Laravel 版本之间的变化还是教程有误。问题,根据本教程:

    https://laravel.com/docs/5.4/blade

    page.blade.php 是不是在侧边栏部分缺少@parent。因此,该文件应为:

    @extends('layouts.master')
    
    @section('title', 'Page Title')
    
    @section('sidebar')
    
        @parent
    
        <p>This is appended to the master sidebar.</p>
    
    @endsection
    
    @section('content')
        <p>This is my body content.</p>
    @endsection
    

    这样,该部分将首先呈现,包括其父部分的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 2020-10-25
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      相关资源
      最近更新 更多