How can I find out which Language was used by Translator in ZF2?
Asked Answered
S

2

0

In my ZF2 application I want to retrieve the language that was used to translate the page. I use the ZendSkeletonApplication as basis. In the Module.php I set the Locale like this:

public function onBootstrap($e){
  $translator = $e->getApplication()->getServiceManager()->get('translator');
  $translator->setLocale(
      Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE'])
    )
    ->setFallbackLocale('en_US');
}

I can retrieve the locale and the fallbackLocale from the Zend\I18n\Translator\Translator, but then I still don't know which one was used for the translation. Since there is also no way (as far as I didn't found one) to find out which languages where actually loaded into the translator. I can't even test myself if a translation exists for the locale.

Maybe I'm missing something here. I hope someone can point that out.

Saturate answered 24/9, 2012 at 15:11 Comment(2)
You could extend the Translator class, overwrite the translate() method and save the used language key in a property.Bayreuth
@DanielM this is an option, but I wanted to check the language in the onBootstrap Event and there the view is propably not rendered. Anyway thank you for you comment.Saturate
S
0

I decided to take the most simple approach. I translate the text of the language too.

Saturate answered 25/9, 2012 at 8:8 Comment(0)
B
2

One option may be retrieving cache object and checking for the existence of the primary locale by recreating the cache key. Looking at the loadMessages() method it seems the cache result would contain the list of available messages.

Otherwise it seems the translate functions simply try the first locale then the fallback.

Brief answered 24/9, 2012 at 16:41 Comment(3)
Yes translate simply tries locale and then fallback, but I would have to do the same. I use Regex for choosing the proper language file and this means I would have to replicate everything what the translator does itself (get the locale from php Locale, go to the language directory, check if the desired language is available, otherwise take fallback.) Its a lot of effort. But anyway I give you +1 for your answer.Saturate
Would something like setting up a dummy translation key in the non-default translation files and checking if that translatable – given that you know the primary locale and fall-back locale, you could tell what file is being used.Brief
If I understand you correctly this is what I have done. See my answer.Saturate
S
0

I decided to take the most simple approach. I translate the text of the language too.

Saturate answered 25/9, 2012 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.