What is the difference between @yield and @include in Laravel?

3

I'm learning Laravel 5.3 , @yield and @include seem to me much the same thing, the only difference I know is that @include injects the variables of parent > and can also include other variables.

  • What is the difference between @yield and @include ?
  • When should I use @yield ?
  • When should I use @include ?
asked by anonymous 29.01.2017 / 00:47

1 answer

6
  

@yield is used to display the contents of a particular section, which is defined by @section which is responsible for defining a content section. An example is the templates that will serve as the 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, there is a base structure for all pages that will use template is with @section is where content will be displayed in the template where @yield , in which case there is a relation between blade . @yield is used when you need to set sections in a template ( or page ) and to work you need that @section matching has content to be loaded.

It has some codes where @yield is used simply as a value pass, example :

@yield('titulo')

and

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

In general, they are used as subheadings of these other views .

  

@include allows you to load other views ( sub-views with% extension nomenclature .blade.php ) into 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

This @include is very particular the page numbers of any table where the data will be processed and validated and if there is an error this code snippet displays the messages of the validation problems.

@include is different in these respects the @yield , because, @include is to include a specific page, @yield is to display contents of a certain section, which can also contain @include .

29.01.2017 / 01:29