Laravel 4:刀片布局中的 if 语句很奇怪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15224545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:35:55  来源:igfitidea点击:

Laravel 4: if statement in blade layout works strange

laravellaravel-4blade

提问by Mr. Sensitive

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

有人可以解释一下,如果我正常请求页面(不是 ajax),为什么我会得到带有打印字符串“@extends('layouts.default')”的空白屏幕?

@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?

我正在尝试解决 Ajax 问题,我不想为每个请求类型创建 2 个模板,而且我确实想使用刀片模板,因此使用控制器布局对我不起作用。我怎样才能在刀片模板中做到这一点?我在看这个Laravel:如何仅渲染模板的一部分?

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

顺便一提。如果我用 ajax 请求它,它会像它应该的那样工作。

回答by Mr. Sensitive

Yes @extends has to be on line 1.

是的@extends 必须在第 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:

我找到了 PJAX 的解决方案。一开始我不确定这是否可以解决我的问题,但确实可以。不知道为什么我害怕失去刀片功能,如果你真的不能以这种方式失去它。如果有人正在使用 PJAX 并且需要使用一个带有和不带有布局的模板,这可能是您的解决方案:

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

回答by Moogblob

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

尝试移至@extends第 1 行,您将看到刀片模板将正确呈现。

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

至于解决ajax问题,我觉得还是把逻辑移回控制器比较好。

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

看看这个线程了解更多信息:http: //forums.laravel.io/viewtopic.php?id=2508

回答by Bakly

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

你仍然可以像这样在拳头线中人手不足

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