简体   繁体   中英

Laravel's Blade template @yield and @section how does it work?

I'm new to Laravel and want to learn how to use the Blade template system properly, but i cant wrap my head around the difference between @section and @yield. I've been reading the docs : https://laravel.com/docs/5.7/blade .

But it's not explaining the differences and how to use them properly. I've been reading posts in other forums too like this one :

https://laravel.io/forum/09-02-2014-using-section-and-yield

But still i'm a bit confused.

For example right now i'm creating an app that have multiple pages with commun pieces between them, so for now i get that i have to create a common layout for this pages, but when to use @section and when do i have to use @yield ?

for example if i have a page like so :

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <title>{{ config('app.name', 'Name') }}</title>
    //Common CSS between pages
    <link href="{{ asset('css/style1.css') }}" rel="stylesheet">
    //Changing CSS between pages
    <link href="{{ asset('css/style2.css') }}" rel="stylesheet">
</head>
<body>
    //the content stay the same !
    <div id="app">
        <span id="some_style">hello world !</span>
    </div>
    <script>
       //common JS
       <script src="{{ asset('script1.js') }}">
       //Changing JS between pages
       <script src="{{ asset('script2.js') }}">
    </script>
</body>
</html>

How can i organise it using the blade templating?

Assuming you 2 templates. Lets call one Base.blade.php and the other one Posts.blade.php .

We'll @extends('base') in Posts .

Using @section in Posts and @yield in Base .

Something like this:

Base

@yield('posts') {# the section called "posts" #}


Posts

@extends('base')

@section('posts')
   Here be posts
@endsection

Whatever is written in posts will be yielded in the base blade.

Think of it as inheritance.

You can imagine it as classes if you will. Where the child class calls a method in the base class.

class Base {
    protected function printSomething($something) {
        echo $something;
    }
}


class Posts extends Base {
    public function BaseWillPrint() {
        $this->printSomething('POSTS');
    }
}

Basically I haven't told you anything that doesn't already exist in the documentation.

Yes, assuming if you have a template you can make the base of template in layouts/app.blade/php and you can make the @yield('anything') and then in your views/main.blade.php you must give @extends('layouts.app') and

@section('anything')
*for dynamic page
@endsection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM