Symfony2基于语言环境创建路由


Symfony2 creating routes based on language locale

我正在为一个多语言站点实现翻译。这一切都很好,但当用户试图改变语言时,语言保持不变。

这是…

index:
    path:  /{_locale}
    defaults: { _controller: HotelIndexBundle:Index:index , _locale:hr}
    requirements:
        _locale: hr|en

在一个小模板中,我必须链接到这个路径与…

path('index');

让我们说我在我的索引页www.example.com(默认为'hr')。然后用户更改为www.example.com/en。它的工作原理。但是当它试图用path('index')返回到hr时,页面返回到相同的www.example.com/en。

还有一个额外的url参数,如www.example.com/en/contact的问题。如何将其更改为www.example.com/hr/contact并留在/联系人页面?

让我们说我在我的索引页www.example.com(默认为)"人力资源")。然后用户更改为www.example.com/en。它的工作原理。但当它尝试返回到hr与path('index'),页面返回到 www.example.com/en相同。

您的配置中应该有以下配置。yml文件:

config.yml

framework:
    translator:      { fallback: "%locale%" }
    default_locale:  "%locale%"

locale参数应该在parameters中定义。yml文件:

parameters.yml

parameters:
    locale: hr

还有一个额外的url参数的问题,如 www.example.com/en/contact。如何将其更改为www.example.com/hr/contact并停留在/联系人页面?

可以这样做:

{% set requestParams = app.request.attributes.get('_route_params') %}
{% set requestRoute = app.request.attributes.get('_route') %}
<a href="{{ path(requestRoute, requestParams|merge({'_locale' : 'en'})) }}">en</a>
<a href="{{ path(requestRoute, requestParams|merge({'_locale' : 'hr'})) }}">hr</a>

看一下JMSi18nRoutingBundle。