简体   繁体   English

翻译不起作用 Symfony

[英]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:你可以看到控制器、index.html.twig、config.yml、messages.es和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 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消息.es

index.1: "CASA"

messages.en消息.en

index.1: "HOME"

So, I don't understand why symfony uses always the locale 'en' when it uses the 'trans' function.所以,我不明白为什么 symfony 在使用“trans”函数时总是使用语言环境“en”。 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.您正在尝试将区域设置设置为Request对象,但在控制器中它对Translator服务没有影响,因为它之前已经配置过了。 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.我想您应该尝试直接为您的Translator服务设置语言环境或创建单独的操作,您只需将语言环境设置为会话并重定向到其他操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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