Symfony:如何从同一个Index路由加载所有路径(在React SPA中使用动态路由)

时间:2018-04-26 14:17:40

标签: reactjs symfony redux

我正在创建一个由Symfony和ApiPlatform支持的SPA,所以我想总是加载我的主路线,尽管URL的路径真实。

我想要这样的事情:

/**
 * {@inheritdoc}
 */
class DefaultController extends Controller
{
    /**
     * @Route("/*", name="homepage")
     *
     * @return Response
     */
    public function indexAction(): Response
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig');
    }
}

在我的意图中,如果网址类似于/path/to/the/spa/page,我还是要加载DefaultController::indexAction()路线。

怎么做? (显然,提供的示例不起作用)。

2 个答案:

答案 0 :(得分:0)

好的,我已经在"照明"之后找到了解决方案。

我记得有可能重写所有网址adding or removing the trailing slash

阅读那篇文章我看到了:

class RedirectingController extends Controller
{
    /**
     * @Route("/{url}", name="remove_trailing_slash",
     *     requirements={"url" = ".*\/$"})
     */
    public function removeTrailingSlash(Request $request)
    {
        // ...
    }
}

因此,为了拦截所有URL,尽管路径,我的DefaultController::indexAction()变为:

class DefaultController extends Controller
{
    /**
     * @Route("/{url}",requirements={"url"=".*"}, name="homepage")
     *
     * @return Response
     */
    public function indexAction(): Response
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig');
    }
}

现在所有网址都由DefaultController::indexAction()处理,尽管有网址路径。

答案 1 :(得分:0)

我建议您改用symfony的事件系统。

订阅The framework 'Microsoft.NETCore.App', version '2.0.0' was not found. - The following frameworks were found: 3.1.5 at [/root/.dotnet/shared/Microsoft.NETCore.App] You can resolve the problem by installing the specified framework and/or SDK. The specified framework can be found at: - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=2.0.0&arch=x64&rid=ubuntu.18.04-x64 kernel.request事件。

kernel.router的情况下,您必须超越kernel.request 哪个专长是Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest()(至少使用32)。

33

对于use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; class SpaSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return [ KernelEvents::REQUEST => ['onKernelRequest', 33], ]; } public function onKernelRequest(RequestEvent $event) { $request = $event->getRequest(); if (!$request->isXmlHttpRequest()) { $html = $this->twig->render('spa.html.twig', [ 'uri' => $request->getUri(), ]); $response = new Response($html, Response::HTTP_OK); $event->setResponse($response); } } } ,至少使用优先级kernel.router

您可以使用1命令来确定为事件及其优先级注册了哪些侦听器。