【问题标题】:Symfony Routing "_locale" parameter not acceptedSymfony 路由“_locale”参数不被接受
【发布时间】:2015-08-28 12:14:04
【问题描述】:

我的 symfony 路由有问题。

对于一个多语言项目,我通过一个用于邮寄的作业队列渲染一个 Twig 模板。在这个模板中是一个到需要“_locale”参数的路由的链接,例如“de”或“en”。我使用函数“{{ url('route', {'_locale': 'de'}) }}”来生成url。

通过渲染模板,我收到以下错误消息:

[Twig_Error_Runtime]
An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("_locale") to generate a URL for route "Route".") in "TemplatePath" at line 5. 

我的错误是什么?

感谢您的帮助

【问题讨论】:

  • 如果您检查分析器,选择的路线是您要寻找的路线吗?
  • 无法检查分析器,因为它是一个 symfony 命令。

标签: symfony routing multilingual


【解决方案1】:

当您通过 CLI 生成 URL 路由时,Symfony 内核缺少 HTTP RequestRouting->RequestContext

这就是为什么,URL 生成器找不到_locale 参数。

要修复它,您必须手动创建RequestContext,因此,在您的命令中:

$this->getContainer()->get('router')
->setContext(
   (new RequestContext())
   ->setParameter('_locale', 'fr')
);

【讨论】:

    【解决方案2】:
    class BaseCommand extends ContainerAwareCommand
    {
        protected function getLocale()
        {
            return $this->getContainer()->get('translator')->getLocale();
        }
    
        protected function render($view, $data)
        {
            return $this->getContainer()->get('templating')->render($view, $data);
        }
    }  
    

    在命令中

    class SomeCommand extends BaseCommand
    {
        ...
        $this->render($view, array_merge($data, ['_locale' => $this->getLocale()])
    }
    

    在视图中

    {{url('any', {param: 'foo'}|merge(_locale is defined ? {'_locale': _locale } : {}))}}
    

    【讨论】:

      【解决方案3】:

      现在是死灵时间 :) 我只是在这里猜测,但您可以尝试一些事情。

      您可以在命令中设置语言环境吗?

      为翻译包设置语言环境:

      $this->getContainer()->get('translator')->setLocale('de');
      

      为此会话设置语言环境:

      $this->getContainer()->get('session')->setLocale('de);
      

      Symfony 4.1 及更高版本的国际化路由

      如果这适用于你,试试这个:

      url('route.de', {'_locale': 'de'}) }}"
      

      您的路线是否将“de”和“en”设置为要求?

      /**
       * Matches /route
       * @Route(
       *     "/route/{_locale}",
       *     requirements={
       *         '_locale': 'en|de'
       *     },
       *     name="route"
       * )
       */
      

      这是一个老问题,但这可能会对某人有所帮助。

      【讨论】:

        猜你喜欢
        • 2016-02-06
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 2012-07-31
        • 1970-01-01
        相关资源
        最近更新 更多