2012-06-26 32 views
4

Symfony2中有一個多語言網站。在基本佈局中,有這樣的語言切換:填寫所有必填參數

<a href="{{ path(app.request.attributes.get('_route'), {_locale: 'en'}) }}">EN</a> 
<a href="{{ path(app.request.attributes.get('_route'), {_locale: 'fr'}) }}">FR</a> 

這可以在不更改當前頁面的情況下正常切換語言。但是,如果有其他參數,則會因爲「缺少必需參數」而引發異常。如何克服這一點?

回答

4

你可以這樣做:

<a href="{{ path(app.request.attributes.get('_route'), app.request.query.all|merge({'_locale': 'en'})) }}">EN</a> 
<a href="{{ path(app.request.attributes.get('_route'), app.request.query.all|merge({'_locale': 'fr'})) }}">FR</a> 

這樣做是合併與現有的查詢參數的參數_locale。

+0

感謝,但它不工作,我無法找到任何東西關於官方文檔中的'app.request.query.all' – seferov

+0

app.request返回一個Request對象(http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Request.html),它有一個查詢字段'ParameterBag)和一個all()方法。我在'_locale'周圍添加了引號,不確定這是否會改變任何內容。 –

+0

'app.request.query.all'返回空數組。我不知道爲什麼。 – seferov

2

這是我的解決方案,Symfony的2.2工作,2.5

<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'en'})) }}">English</a> 
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'fr'})) }}">Français</a> 
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'es'})) }}">Español</a> 

這是我的解決方案,Symfony的2.0工作,2.1

<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'en'})) }}">English</a> 
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'fr'})) }}">Français</a> 
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'es'})) }}">Español</a>