Laravel 4: if statement in blade layout works strange

安稳与你 提交于 2019-12-13 13:08:27

问题


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.


回答1:


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');
  }
}



回答2:


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




回答3:


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

@extends((Request::ajax())?"layout1":"layout2")


来源:https://stackoverflow.com/questions/15224545/laravel-4-if-statement-in-blade-layout-works-strange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!