1

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

T. Cem Yılmaz
  • 500
  • 9
  • 30
  • 1
    Use `Request::ajax()` to determine where a request is an ajax request. Because layout needs to be the very first thing in a view, I'd recommend wrapping your whole layouts.master file in an if statement like `@if ( ! Request::ajax() ) ... layout ... @endif` – David Feb 08 '13 at 18:31
  • 1
    In your controller you should be using `Request::ajax()` then have a `view` which uses a particular layout. That `view` can then nest another `view`. That nested `view` can be a single template to edit then be used via AJAX calls or non AJAX calls. – Cristian Feb 20 '13 at 13:42
  • Is this Laravel 3 or Laravel 4? – rmobis Mar 02 '13 at 03:34

3 Answers3

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.

John
  • 486
  • 5
  • 15
0

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).

angus
  • 128
  • 1
  • 1
  • 5
0

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.

Yaroslav
  • 3,168
  • 1
  • 15
  • 14