0

This may seem like an odd question, but I am new to Laravel and have a lot of trouble finding the right syntax in the official documentation. Here is an example. I was using the following blade syntax to try and have a conditional view:

@if (condition)
  @extends 'layouts.regular'
@else
  @extends 'layouts.special'
@endif

This did not work. I then went to the blade documentation on the Laravel site and read through the Extending a Layout section. All seemed well and I spent 10 minutes debugging my code and trying to find out if I did something wrong. It all seemed correct, so I then resorted to Google and found this thread.

From the comments I understood that:

  • The @extends statement must be the first line in a blade template
  • You can only use a conditional extend by using a ternary expression

While this solved my problem, it took too long to find. I still can't figure out WHERE in the official documentation this is mentioned. Am I using the official documentation wrong? Is there other, more extensive documentation out there? I keep feeling that the online documentation is very brief and often does not explain important details on syntax or exceptions...

Mogsdad
  • 44,709
  • 21
  • 151
  • 275

1 Answers1

0

@extends always comes in the first line of blade, it is used to define the layout e.g.

Assume we have master.blade.php

<html>
    <head>
    </head>
    <body>
        @yield('content')
    </body>
</html>

Then we have page.blade.php

@extends('master') // this one says this page will be placed in master.blade.php
@section('content') // find the line that says @yield('content') and replace it with...
    <h1> Hello World </h1>
@stop

Now, if you have many layouts and you want to share the content with it, you can achieve that programatically away from blade.. take this example

Assume we have master.blade.php

<html>
    <head>
        <title>Master</title<
    </head>
    <body>
        @yield('content')
    </body>
</html>

and we have master2.blade.php

<html>
    <head>
        <title>Master 2</title>
    </head>
    <body>
        @yield('content')
    </body>
</html>

and we have page.blade.php

@section('content')
    <h1>Hello World</h1>
@stop
// note that we have no @extends()

now in the controller we do something like this

if($cond) 
{
    $layout = view('master');
}
else 
{
    $layout = view('master2');
}

$page = view('page');
$layout->content = $page; 

return $layout;

Note that we are using $layout->content because both layouts are yielding content in @yield('content')

UX Labs
  • 1,481
  • 14
  • 29
  • Thanks but please note that my question is not about this particular issue. It is about finding these kinds of things in the official documentation. Could you point me to the Laravel documentation that explains this? –  Jan 20 '16 at 08:14