简体   繁体   中英

Symfony2: How to set default locale and case insensitive translation

I am just starting using symfony2 and facing some difficulty need helps from expert like you guys.

Question 1: How to set the default locale and fallback locale so that people try to hit something like www.example.com/home or www.example.com/fr/home (not supported locale) will redirect to www.example.com/cn/home?

I have read a lot from symfony2 document ( http://symfony.com/doc/current/book/translation.html ) and also searching on google but I still can't make it works. Not only default locale not working, the fallback locale also not working. For example, when user try to enter www.example.com/fr/home which is not supported by my app, it supposes to redirect the user to www.example.com/cn/home but it fails to do so.

I try to clear cache also but it seem like not working.

Question 2: How to match the translation key in case insensitive?

For example, in my translation file ("message.cn.yml") contains

Welcome: 欢迎

So in my twig template, I use {{ ' Welcome ' | trans }} it will help me convert to 欢迎 but when I use {{ ' welcome ' | trans }} it will not convert. Is there any ways to make it to case insensitive so I do not need to purposely add in the key " welcome : 欢迎" to the message.cn.yml file.

Your help and suggestion is very much appreciated. Thank you.

Below are my app files for your reference:

Translations file:

在此输入图像描述

Parameters file:

在此输入图像描述

Config file:

在此输入图像描述

Routing file in the particular bundle("Acme/DemoBundle"):

在此输入图像描述

Twig file:

在此输入图像描述

Here is the result when I hit

  1. localhost/locale/web/app_dev.php/

在此输入图像描述

  1. localhost/locale/web/app_dev.php/en

在此输入图像描述

  1. localhost/locale/web/app_dev.php/cn

在此输入图像描述

  1. localhost/locale/web/app_dev.php/fr

在此输入图像描述

You can set locale for a request:

 $this->container->get('request_stack')->getCurrentRequest()->setLocale($locale);

and you can set locale per request using a request listener: http://symfony.com/doc/current/cookbook/service_container/event_listener.html#request-events-checking-types

for your second question you can add conversion to lower case:

   {{ 'WELCOME'|lower | translate}}

or you can create your own customized twig extension that is doing the translation and other stuff in between: http://symfony.com/doc/current/cookbook/templating/twig_extension.html

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