Home > database >  Using multiple @yields with Laravel
Using multiple @yields with Laravel

Time:03-12

I have worked with Laravel before and have some applications that utilize multiple @yields inside of the template files, probably not best practice but I'm still learning a bunch.

I recently started a fresh installation to begin a new project and I'm trying to get a navbar and home page configured together using the templating engine and it looks like such:

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

The issue that I'm running into is that only the @yield('content') works the other one doesn't appear to be read at all, I've done this in the past but I'm not sure what might be causing it. Any help would be greatly appreciated!

CodePudding user response:

You can pass empty string as default value for yield like so :

@yield('content2' , '')

CodePudding user response:

Based on my tests, your example demo in the question works fine without any issues. Template inheritance.

Nonetheless, you may try making use of the "modern" anonymous components.

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>
  • Related