What’s the difference between @Yield and @include on Laravel?

Asked

Viewed 10,928 times

8

I’m learning Laravel 5.3, @yield and @include seem very much the same to me, the only difference I know is that @include injects the variables of father and may also include other variables.

  • What’s the difference between @yield and @include?
  • When should I wear @yield?
  • When should I wear @include?

1 answer

17


@yield is used to display the contents of a particular section, which is defined by @section that is responsible for defining a content section. An example are the templates which will serve as a basis for several pages.

Example administrative sector:

master.blade.php (template):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">    
</head>
<body>
<div class="container">
    <div class="panel panel-default">        
        <div class="panel-body">
            @yield('content')
        </div>
    </div>
</div>
</body>
</html>

roles.blade.php:

@extends('master')
@section('content')
    //Contéudo que será diferente para outras páginas
@stop

in this example, it has a base structure for all pages that will use template is with @section is where the content will be displayed in the template where it is @yield, in that case there is the relationship between those blade. @yield is used when you need to define sections in a template (or page) and to function @section corresponding has contents to be loaded.

There are some codes where @yield is simply used as a passage of value, example:

@yield('titulo')

and

@section('titulo', 'Novo titulo');

are generally used as sub-titles of these other views.


@include allows loading other views (sub-views with the extension nomenclature .blade.php) in a view and use the variables that were sent to that view.

Example:

erros.blade.php

@if(isset($errors) && count($errors))
    <div class="alert alert-danger" style="margin-top: 6px;">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

cadastro.blade.php

@extends('master')
@section('content')
    @include('errors')
@stop

that @include is very particular the registration pages of any table, where the data will be processed and validated and if there is any error this code snippet displays the messages of validation problems.

@include is different in these aspects to @yield, because, @include is to include a specific page, already @yield is to display content from a particular section, which may also contain @include.

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.