Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: if statement in blade layout works strange

Could someone explain me why I get blank screen with printed string "@extends('layouts.default')" if I request page normally (not ajax)?

@if(!Request::ajax())
  @extends('layouts.default') 
  @section('content')
@endif
Test
@if(!Request::ajax())
  @stop
@endif

I'm trying to solve problem with Ajax, I don't want to create 2 templates for each request type and also I do want to use blade templates, so using controller layouts doesn't work for me. How can I do it in blade template? I was looking at this Laravel: how to render only one section of a template?

By the way. If I request it with ajax it works like it should.

like image 458
Mr. Sensitive Avatar asked Mar 05 '13 13:03

Mr. Sensitive


3 Answers

Yes @extends has to be on line 1.

And I found solution for PJAX. At the beginning I was not sure this could solve my problem but it did. Don't know why I was afraid to lose blade functionality if you actually can't lose it this way. If someone is using PJAX and needs to use one template with and without layout this could be your solution:

protected $layout = 'layouts.default';

public function index()
{
  if(Request::header('X-PJAX'))
  {
    return $view = View::make('home.index')
      ->with('title',  'index');
  }
  else
  {
    $this->layout->title = 'index';
    $this->layout->content = View::make('home.index');
  }
}
like image 66
Mr. Sensitive Avatar answered Oct 23 '22 05:10

Mr. Sensitive


Try moving @extends to line 1 and you will see the blade template will render properly.

As for solving the ajax problem, I think it's better if you move the logic back to your controller.

Example:

…
if ( Request::ajax() )
{
    return Response::eloquent($books);  
} else {
    return View::make('book.index')->with('books', $books);
}
…

Take a look at this thread for more info: http://forums.laravel.io/viewtopic.php?id=2508

like image 22
Moogblob Avatar answered Oct 23 '22 04:10

Moogblob


You can still run your condition short handed in the fist line like so

@extends((Request::ajax())?"layout1":"layout2")
like image 23
Bakly Avatar answered Oct 23 '22 06:10

Bakly