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
255 views
in Technique[技术] by (71.8m points)

php - Advanced customization of translations in Symfony2

I have a Symfony2 project and I am using Translation component for translating text. I have all translations in yml file like so

translation-identifier: Translated text here

Translating text looks like this from Twig

'translation-identifier'|trans({}, 'domain')

The thing is, in some cases I would like to have two different texts for same translation (not for pluralization). Here's how I would like it to work:

  1. Define two texts in yml file for translations that need to have different texts. Each would have it's own unique suffix

    translation-identifier-suffix1
    
    translation-identifier-suffix2
    
  2. Define a global rule that would define which suffix should be choosen. Psuedocode below:

     public function getSuffix() {
       return rand(0, 10) < 5 ? '-suffix1' : '-suffix2';
     }
    
  3. Twig (and PHP) would look the same - I would still specify just the identifier without suffix. Translator would then append suffix to the identifier and try to find a match. If there would be no match it would try to find a match again without suffix.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

AFAIK, Translator component doesn't support it.

But if you want same kind of behavior, you could do by overriding the translator service.

1) Override the service

# app/config/config.yml
parameters:
    translator.class:      AcmeHelloBundleTranslationTranslator

First, you can set the parameter holding the service's class name to your own class by setting it in app/config/config.yml. FYI: https://github.com/symfony/FrameworkBundle/blob/master/Resources/config/translation.xml

2) Extend the translator class provided symfony framework bundle. FYI: https://github.com/symfony/FrameworkBundle/blob/master/Translation/Translator.php

3) Overwrite the trans function which is provider by translator component. https://github.com/symfony/Translation/blob/master/Translator.php

Hope this helps!


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

...