Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

php - Set locale in Symfony 2.1

I am trying to have a language switcher on my symfony 2.1 website.

I followed the official documentation, set the translation files but setting the locale with $request->setLocale('en_US'); doesn't seem to work. After some research, I found this question which provides a beginning of an answer with this listener technique.

However, I still don't manage to have it working, I'm not so sure about my listener declaration, is something wrong with it?

My controller:

public function englishAction(Request $request)
{
    $this->get('session')->set('_locale', 'en_US');
    return $this->redirect($request->headers->get('referer'));
}

Service declaration in config.yml:

services:
    my_listener:
        class:        "FKMyWebsiteBundleListenerLocaleListener"

My routing:

homepage:
    pattern:  /{_locale}
    defaults: { _controller: FKMyWebsiteBundle:Default:index, _locale: en }
    requirements:
        _locale: en|fr|cn
about:
    pattern:  /{_locale}/about
    defaults: { _controller: FKMyWebsiteBundle:Default:about, _locale: en }
    requirements:
        _locale: en|fr|cn
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The declaration of the LocaleListener in yml (inspired by the current declaration of the new LocaleListener: vendorsymfonysymfonysrcSymfonyBundleFrameworkBundleResourcesconfigweb.xml)

services:
    my_listener:
        class: "FKMyWebsiteBundleListenerLocaleListener"
        arguments: [%locale%]
        tags:
            -  { name: kernel.event_subscriber }

Some snippets:

A language switcher in your template:

{% for locale in ['en', 'fr', 'cn'] %}
    <li {% if locale == app.request.locale %}class="active"{% endif %}>
        <a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : locale})) }}">{{ locale }}</a>
    </li>
{% endfor %}

A redirection with locale change from a controller:

$LocalizedUrl = $this->get('router')->generate(
    $request->attributes->get('_route'), 
    ['_locale' => $locale] + $request->attributes->get('_route_params')
);

return new SymfonyComponentHttpFoundationRedirectResponse($LocalizedUrl);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...