Laravel usage “@layout” in Ajax Requests

老子叫甜甜 提交于 2019-12-24 09:14:25

问题


Hi there stackoverflow!

In my laravel views I am using a default layout by calling

@layout('layouts.default')

to the same controller I am sending Ajax Requests yet I can't put 'if' to @layout if its a ajax call. Because if ajax request has made to controller it also produce header, footer and content(header and footer are in default layout). So to avoid this I made one copy without @layout of my view.

However its so boring to edit two files for making changes. Can't I add a code to my view something like that?:

@if(!$ajaxrequest)
 @layout('layouts.master')
@endif

I want this because my codes in controllers are too messy


回答1:


A slight variation is to put the logic for the layouts in your main layout template. e.g.

layouts/app.blade.php:

@if (Request::ajax()) 

    @include('layouts.ajax-app')

@else

    @include('layouts.default-app')

@endif

Your views just extend the main layout as usual e.g.

@extends('layouts.app')

@section('content')
    Content goes here...
@endsection

And then create a default layout file (default-app.blade.php) and an ajax layout file (ajax-app.blade.php). The advantage of doing it this way is that any of your blade templates can be loaded via Ajax, without having to clutter up controller methods with lots of duplicated logic.




回答2:


You can't have the @layout call after the if statement like that (see the notice in red under "Blade Templating" in the docs. You'll have to set the public $layout and call $this->layout->nest instead of View::make (see "The Basics" on the page linked to above).




回答3:


You can use something like this in your view template:

@extends( 'layouts.' . (isset($layout) ? $layout : 'default'))

Also apply check in your controller(or Supercontroller) for AJAX request, if it is set $layout variable to needed layout. Otherwise "default" layout will be taken.



来源:https://stackoverflow.com/questions/14775847/laravel-usage-layout-in-ajax-requests

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