Difference between @yield and @include in Blade de Laravel

2

Hello people wanted to know if there is any technical difference, in principle and for the function that I give them, they would be working the same.

It seems clearer to use @include . but I would like to know if there are any details that I should know not to abuse him.

    
asked by Cidius 23.09.2016 в 17:39
source

2 answers

1

@yield will search for a section established in the current page (or view) and will show it in that place, you can also add a default value in case there is nothing in that section.

Thus @yield('titulo', 'Mi sitio') will include what is defined in @section Blog @endsection in a view (the text Blog in this case), if nothing is defined, it will show the text My site.

The source code of @yield is:

protected function compileYield($expression)
{
    return "<?php echo \$__env->yieldContent{$expression}; ?>";
}

public function yieldContent($section, $default = '')
{
    $sectionContent = $default;

    if (isset($this->sections[$section])) {
        $sectionContent = $this->sections[$section];
    }

    $sectionContent = str_replace('@@parent', '--parent--holder--', $sectionContent);

    return str_replace(
        '--parent--holder--', '@parent', str_replace('@parent', '', $sectionContent)
    );
}

@include will simply include another view in the current one, so that @include('blog.articulo') will find the file views\blog\articulo.blade.php and will include it in the current view, all its contents.

The source code of @include is:

protected function compileInclude($expression)
{
    if (Str::startsWith($expression, '(')) {
        $expression = substr($expression, 1, -1);
    }

    return "<?php echo \$__env->make($expression, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
}
    
answered by 23.09.2016 / 18:37
source
0

What I see as a difference is how it is implemented in the code, for example.

If you have a @include like implementing in php is that it is only for a specific code that you call from another site. instead the @yield you put a "name" to put it in some way. That is to say @yield('contenido') and that content can be shown from other views that are referenced to that @yield .

Obviously in code you do the extension to where that yield is.

That's how I see it. The @yield for many calls and the @include for a single specific one.

    
answered by 23.09.2016 в 18:18