0

如何在树枝模板中使用语言环境的最佳做法是什么:

  • 如何在语言之间切换(在模板中使用语言切换器)以及如何通过更改语言来保留现有 URL
  • 如何使用语言环境支持创建 URL

例如:我有 2 种语言(ESEN),默认语言是 ES,对于我的主页,我 在我的控制器文件中为/(对于默认语言,在本例中为 ES)和(对于其他语言)创建 2 个路由注释。/{_locale}/

现在我需要将我的树枝模板的语言环境参数添加到我的 URL 中,但前提是我不会使用我的默认语言。

手动重写 URL 工作正常,但是当我在我的树枝模板上创建时,有什么简单的方法可以将语言环境参数添加到 URL 吗?

变量 locale 的实际值可以传递给 Controller,但是有没有更好的方法在 twig 中获取它?

编辑:

/**
 * @Route(
 *     "/{_locale}/branches", name="branches",
 *     requirements={"_locale":"%app_locales%"}
 *     )
 * 
 */
public function indexAction(Request $request) {
    return $this->render('branches/index.html.twig');
}

index.html.twig

<li class="{% if app.request.attributes.get('_route') starts with 'branches' %}active{% endif %}">
                    <a href="{{ path('branches') }}" class="">{{ 'header.menu.branches'|trans }}</a>
                </li>

我有

没有找到“GET /branches”的路由我使用这个 URL http://localhost:8080/en/branches(工作正常)和http://localhost:8080/branches(错误)我必须使用这样的东西:

/**
 * @Route(
 *     "/branches/", name="branches_def",
 *     defaults={"_locale":"%locale%"},
 *     )
 * @Route(
 *     "/{_locale}/branches/", name="branches",
 *     requirements={"_locale":"%app_locales%"}
 *     )
 * 
 */
public function indexAction(Request $request) {
    return $this->render('branches/index.html.twig');
}

使用路径生成 URL 是可以的,但是如果我从浏览器中的 URL 中删除语言环境参数,我会收到此错误。

非常感谢任何有用的建议

4

2 回答 2

2
  1. translator: { fallbacks: ['%locale%'] }在 config.yml 中取消注释行
  2. 在同一个文件中声明所需的变量:

    parameters:
        locale: en
        app.locales: en|lv|ru
    
  3. 在 routing.yml 中声明您需要的路由,如下所示:

    contact_us:
        path: /{_locale}/contact
        defaults:
            _controller: 'AppBundle:Default:contact'
            _locale: '%app.locales%'
    
  4. 如果使用_locale 占位符声明,则不{{ path('another_route') }}带参数使用。another_route也供单文本翻译使用{{ 'home.title'|trans }}
于 2017-07-22T13:46:46.067 回答
1

将您的语言环境保存到 cookie 中,然后在您的 twig 文件中创建链接,例如<a href="{{ path('your-path-name', {'locale': app.request.cookies.get('LOCALE_COOKIE')}) }}">

如果未设置 cookie,我不确定您是否会收到错误或空值(这将帮助您在控制器路由中使用默认语言环境),但您应该尝试一下。

于 2017-07-22T07:23:07.007 回答