Mission
Mission

Reputation: 1297

Laravel 3, render only one section (for ajax)

I'd like to reuse my templates and would like to return only one rendered section as an ajax response (html table) which belongs to the "content" section (index.blade.php).

@section('content')
html...
@endsection

I've created another layout called ajax (ajax.blade.php) which contains only:

@yield('content')

My controller:

class Some_Controller extends Base_Controller {

    public $restful = true;
    public $layout = 'layouts.main';

public function get_index (){
if ( Request::ajax() )
 $this->layout = 'layouts.ajax';

$view = View::make('some.index')->with('data', 'shtg');

$this->layout->content = $view;
}
}

It works when I request the route via normal GET request... but when I request it via ajax I get an error:

Attempt to assign property of non-object

on the line containing

$this->layout->content = $view;

I've also tried

return Section::yield('content');

Which returns empty document.

Is there a way to return rendered section? I've searched over the forums and couldn't find anything apart from:

http://forums.laravel.io/viewtopic.php?id=2942

Which uses the same principle and doesn't work for me (I've tried all the variations mentioned on the link above).

Thanks!

Upvotes: 0

Views: 1212

Answers (1)

Phill Sparks
Phill Sparks

Reputation: 20889

You appear to be mixing blade templates with controller templates. If you wish to use controller layouts (my preference) then remove the @section('content') and @endsection, and replace @yield('content') with $content.

However, that is not your entire problem. The following line is picked up by the layout method and converted into a real view...

public $layout = 'layouts.main';

You could easily extend the layout function in your controller, adding a layout_ajax attribute like this...

/**
 * The layout used by the controller for AJAX requests.
 *
 * @var string
 */
public $layout_ajax = 'layouts.ajax';

/**
 * Create the layout that is assigned to the controller.
 *
 * @return View
 */
public function layout()
{
    if ( ! empty($this->layout_ajax) and Request::ajax() )
    {
        $this->layout = $this->layout_ajax;
    }
    return parent::layout();
}

Upvotes: 1

Related Questions