在 Laravel 中使用多个 @yield

Using multiple @yields with Laravel

我之前曾与 Laravel 合作过,并且有一些应用程序在模板文件中使用多个 @yield,这可能不是最佳实践,但我仍在学习很多东西。

我最近开始全新安装以开始一个新项目,我正在尝试使用模板引擎将导航栏和主页配置在一起,它看起来像这样:

master.blade.php

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test</title>
</head>
<body>
    @yield('content')
    @yield('content2')
</body>
</html>

welcome.blade.php

@extends('layouts.master')

@section('content')
    <h1>Test</h1>
@endsection

test.blade.php

@extends('layouts.master')

@section('content2')
    <h1>Test2</h1>
@endsection

我 运行 遇到的问题是只有 @yield('content') 有效,另一个似乎根本没有被阅读,我过去曾这样做过,但我我不确定是什么原因造成的。任何帮助将不胜感激!

您可以像这样传递空字符串作为 yield 的默认值:

@yield('content2' , '')

根据我的测试,您在问题中的示例演示工作正常,没有任何问题。 Template inheritance.

不过,您可以尝试使用“现代”匿名组件。

Anonymous Components

Similar to inline components, anonymous components provide a mechanism for managing a component via a single file. However, anonymous components utilize a single view file and have no associated class. To define an anonymous component, you only need to place a Blade template within your resources/views/components directory.

resources/views/components/layouts/master.blade.php

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>{{ $title ?? 'Test' }}</title>
    </head>
    <body>
        {{ $content ?? '' }}
        {{ $content2 ?? '' }}
    </body>
</html>

resources/views/welcome.blade.php

<x-layouts.master>

    <x-slot name="title">
        Test
    </x-slot>

    <x-slot name="content">
        <h1>Test</h1>
    </x-slot>

</x-layouts.master>

resources/views/test.blade.php

<x-layouts.master>

    <x-slot name="title">
        Test2
    </x-slot>

    <x-slot name="content2">
        <h1>Test2</h1>
    </x-slot>

</x-layouts.master>