Laravel: how to render only one section of a template?

前端 未结 4 1482
深忆病人
深忆病人 2020-12-05 00:50

I\'m trying to use pjax on my site, which means that for a full page request I render the whole template (this is normal behaviour), but on pjax requests I would like to ren

4条回答
  •  时光取名叫无心
    2020-12-05 01:28

    This is kind of an old question but I would like to throw down another solution.

    Lets say you have a view layout called main.blade.php and another view that extends main called page.blade.php

    main.blade.php

    
    
    
        My Title
    
        @section('head')
            
        @show
    
    
    
        @yield('content')
    
        @section('footer')
            
            
        @show
    
    
    

    page.blade.php

    @extends('main')
    
    @section('content')
        
    This is a rendered page
    @stop

    Just a simple basic template to get things started. In your controller if you return a View::make('page') you will get the complete HTML but Laravel provides a way to return specific sections. Here is an example of how to display the content you want based on if its an ajax call or not from within your controller:

    my_controller.php

    function get_index() {
        $view = View::make('page');
    
        if(Request::ajax()) {
            $sections = $view->renderSections(); // returns an associative array of 'content', 'head' and 'footer'
    
            return $sections['content']; // this will only return whats in the content section
    
        }
    
        // just a regular request so return the whole view
    
        return $view;
    }
    

    Now when you make an ajax call to the page it will only return the content section rather than the entire HTML.

提交回复
热议问题