Laravel 覆盖渲染器视图

Laravel override renderer view

我希望在有视图 ('view') 的地方发送 ajax 请求,而不是返回原始视图 returns a JSON

像那样:

/**
     * @param \Illuminate\Contracts\View\View $view
     * @return \Illuminate\Http\JsonResponse
     */
    protected function ajaxResponse (View $view)
    {
        return response()->json([
            'id' => $view->getData()['page'],
            'title' => $view->getData()['title'],
            'content' => $view->renderSections()['content'],
            'replacepage' => null,
        ]);
    }

但我完全不知道该怎么做我不想在每个控制器中重复自己

我尝试用我的视图替换视图,但它不起作用,因为我希望一切正常,但我无法恢复我页面的部分

<?php

namespace App\Extensions\View;

use Illuminate\View\View;

class AjaxView extends View
{
    /**
     * Get the contents of the view instance.
     *
     * @return string
     * @throws \Throwable
     */
    protected function renderContents()
    {
        if(request()->ajax()) {
            echo $this->getResponse($this->getData());
            exit;
        }

        return parent::renderContents();
    }

    /**
     * @param array $data
     * @return false|string
     */
    public function getResponse (array $data = [])
    {
        return json_encode([
            'id' => $data['page'],
            'title' => (!empty($data['title']) ? $data['title'] . ' - ' . config('app.name') : null),
            'content' => $this->renderSections()['content'],
            'replacepage' => null
        ]);
    }

}

这个returns:

也许你可以这样做: 在app/Http/Controllers/Controller.php中添加方法response();

protected function view($viewPath, $content, $status = 200, array $headers = [])
{
        if(request()->ajax()) {
            return response()->json($content, $status, $headers);
        }

        return view($viewPath, $content);
}

您的控制器方法可以这样使用:

public function create()
{
  // logic
  return $this->view('view_path', $data);
}

我已经通过

改变了你的功能
protected function ajaxView(string $viewPath, array $content = [], int $status = 200, array $headers = [])
    {
        $view = view($viewPath, $content);

        if(request()->ajax()) {
            dd($view->getData());
            return response()->json([
                'id' => $this->view->getData()['page'],
                'title' => $this->view->getData()['title'],
                'content' => $this->view->renderSections()['content'],
                'replacepage' => null,
            ], $status, $headers);
        }

        return $view;
    }

但是如果记录不为空,如果我将 dd() 放在我的外部,则 dd() 记录数组为空