【问题标题】:Symfony Automatism in URL reWriteURL 重写中的 Symfony 自动化
【发布时间】:2017-11-16 10:59:54
【问题描述】:

我的网站名称是“vg” 开发网址是:“http://localhost/vg/web/app_dev.php/” vg\app\config\routig.yml 中设置的前缀定义为:“/gallery”

所以问题是:如果 url 只是“http://localhost/vg/web/app_dev.php/”,如何自动将前缀(图库)添加到用户或进程给出的 url 中

(.../gallery/ 相当于传统的索引页。)

谢谢

【问题讨论】:

    标签: php symfony url url-rewriting root


    【解决方案1】:

    routing.yml 中,您可以添加一个简单的重定向:

    # redirecting the root
    root:
        path: /
        defaults:
            _controller: FrameworkBundle:Redirect:urlRedirect
            path: /gallery
            permanent: true
    

    参考:https://symfony.com/doc/current/routing/redirect_in_config.html

    如果前缀(此处为gallery)是配置值,则使用控制器方法进行重定向:

    /**
     * @Route("/", name="index")
     */
    public function indexAction(): Response
    {
        $urlPrefix = 'gallery'; // get this value from wherever appropriate, e.g.
                                // a service, class constant, a value from parameters.yml
    
        return $this->redirectToRoute('some_route', [
            'prefix' => $urlPrefix
        ]);
    }
    

    假设你想要代码中的前缀值,那么它不应该是配置的路由前缀,而是适当的路由器参数:

    /**
     * @Route("/{prefix}", name="some_route")
     *
     * @return Http\Response
     */
    public function someAction($prefix): Response
    {
        // do things with $prefix
    
        return $this->render('view.html.twig');
    }
    

    这两个动作可以在同一个控制器中。

    【讨论】:

    • 在 vg\app\config\routig.yml 文件中的前缀标签上设置了“gallery”这个词。我不想设置“/gallery”,但我想使用这个“前缀”参数的内容所以,“前缀”有一个代表“元数据”,可以在标签上的正确位置使用“路径”在您之前的答案中? like : path: {prefixe} // 是一个例子
    • @PhilippeGODEFROY 好的,所以真正的前缀是未知的,但可以作为某种配置参数使用?
    • 我做到了。所以我有: # src/VG/paintBundle/Resources/config/routing.yml vg_paint_index: path: / defaults: _controller: VGpaintBundle:Paints:index path: /gallery Permanent: true 当我询问 URL 时:localhost/vg/web/app_dev.php 我得到: '没有为“GET /”找到路由'
    • 函数没问题,但很抱歉,我应该在哪个脚本中编写它?在我的捆绑控制器中?以及如何检索在 vg\app\config\routig.yml 文件中的前缀标记上设置的值(/gallery)
    • 是的,它需要在控制器中。就我个人而言,我会把它放在你的包中最通用的控制器中。
    【解决方案2】:

    好的,我找到了。我要真诚地感谢你。

    1. vg\app\config\routing.yml文件中
    vg_paint: 资源:'@VGpaintBundle/Resources/config/routing.yml' 前缀:/画廊 根: 小路: / 默认值: _controller: FrameworkBundle:Redirect:urlRedirect 路径:/画廊 永久:真实
    1. # src/VG/paintBundle/Resources/config/routing.yml 文件中
    vg_paint_home: 小路: / 默认值: _控制器:VGpaintBundle:油漆:索引 页数:0 要求: 页:\d* vg_paint_index: 路径:/{页面} 默认值: _控制器:VGpaintBundle:油漆:索引 页数:0 要求: 页:\d* vg_paint_view: 路径:/paints/{id} 默认值: _控制器:VGpaintBundle:油漆:视图 编号:0 要求: 编号:\d+

    现在,如果我打电话给http://localhost/vg/web/app_dev.php(最后有或没有/),“画廊”这个词就会出现在这个网址的末尾 @+

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      相关资源
      最近更新 更多