简体   繁体   中英

Translation doesn't work Symfony

I'm trying to translate my platform. First I made a simple layout for trying the trans fuction. When I make sure about it, I will make it for the real case. you can see the controller, index.html.twig, config.yml, messages.es and messages.en:

....

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Translator;

class DummyController extends Controller
{
    /**
     * @Route("/prova",name="role_public_dummy")
     * @Template()
     */
    public function indexAction(Request $request)
    {
        //$locale = $request->getLocale();
        $request=$this->getRequest();
        $locale = $request->getPreferredLanguage();//catching browser language
        $request->setLocale($locale);
        $this->get('session')->set('_locale', $locale);

        return array();

    }

}

index.html.twig

{% trans %}index.1{% endtrans %}

config.yml

framework:
    #esi:             ~
    translator:      { fallback: "%locale%" }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    templating:
        engines: ['twig']
        #assets_version: SomeVersionScheme
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id:  ~
    fragments:       ~
    http_method_override: true

messages.es

index.1: "CASA"

messages.en

index.1: "HOME"

So, I don't understand why symfony uses always the locale 'en' when it uses the 'trans' function. It's like it doesn't catch the locale of the session.

You are trying to set locale to Request object, but in controller it takes no effect on Translator service so as it has been already configured earlier. I guess you should try setting locale for your Translator service directly or creating separate action where you will be only setting locale to session and redirecting to other action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM