【问题标题】:Laravel 3, render only one section (for ajax)Laravel 3,只渲染一个部分(用于 ajax)
【发布时间】:2013-04-29 15:31:06
【问题描述】:

我想重用我的模板,并希望只返回一个呈现的部分作为属于“内容”部分 (index.blade.php) 的 ajax 响应(html 表)。

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

我创建了另一个名为 ajax (ajax.blade.php) 的布局,其中仅包含:

@yield('content')

我的控制器:

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

当我通过普通 GET 请求请求路由时,它可以工作......但是当我通过 ajax 请求它时,我得到一个错误:

Attempt to assign property of non-object

在包含

的行上
$this->layout->content = $view;

我也试过

return Section::yield('content');

返回空文档。

有没有办法返回渲染部分?我搜索了论坛,除了:

之外找不到任何东西

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

它使用相同的原理,但对我不起作用(我已经尝试了上面链接中提到的所有变体)。

谢谢!

【问题讨论】:

    标签: php laravel laravel-3


    【解决方案1】:

    您似乎将blade templates 与controller templates 混合在一起。如果您希望使用控制器布局(我的偏好),请删除@section('content') 和@endsection,并将@yield('content') 替换为$content。

    但是,这不是您的全部问题。下面这行被layout method捡起来,转换成真实的视图……

    public $layout = 'layouts.main';
    

    您可以轻松地在控制器中扩展布局功能,添加这样的 layout_ajax 属性...

    /**
     * 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2014-09-18
      • 2013-01-29
      • 2017-05-03
      相关资源
      最近更新 更多