在我的异常中,如果在控制器上进行异常调用,如何在twig中进行重定向,如何重定向

时间:2017-12-16 20:13:15

标签: symfony twig-extension

我需要从twig中呈现的控制器重定向,该示例在路径“/ login_form”中可用

关于生产不起作用,开发工作,我很困惑如何让这些代码在生产中工作?

Symfony 3.4

代码仅作为测试的示例

services.yml:

services:
    kernel.listener.redirectexception:
        class: AppBundle\EventListener\RedirectExceptionListener
        arguments:
            - "@router"
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

DefaultController.php:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Exception\RedirectException;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
        ]);
    }

    /**
     * @Route("/login", name="login")
     */
    public function loginAction(Request $request)
    {
        if ($this->getUser()) {
          throw new RedirectException('This user does not have access to this section.');
        }
        return $this->render('default/login.html.twig', []);
    }

    /**
     * @Route("/login_form", name="login_form")
     */
    public function loginFormAction(Request $request)
    {
        return $this->render('default/login_form.html.twig', []);
    }
}

RedirectExceptionListener.php:

<?php

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use AppBundle\Exception\RedirectException;
use Symfony\Component\Routing\RouterInterface;

class RedirectExceptionListener
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ((!$event->getException()->getPrevious() instanceof RedirectException)
              && (!$event->getException() instanceof RedirectException)) {
            return;
        }
        $response = new RedirectResponse($this->router->generate('homepage'));
        $event->setResponse($response);
    }

}

login_form.html.twig:

{{ render(controller('AppBundle:Default:login')) }}

0 个答案:

没有答案