lunedì, gennaio 14, 2013

I18n with Yii

Curious about Yii, I wanted to test its I18n features.

The documentation on the web site is a good starting point, but some hints are missing, and I had to google a bit to find out.

You can see which language is currently set by accessing the value of Yii::app()->language.

If needed, you can also change the value, for instance to view a string in different languages. For instance, this code in a view:

<?php foreach(array('en', 'it', 'pl') as $lang): ?>
  <?php Yii::app()->language=$lang ? ?>
  <p><?php echo $lang ? ?>:
  <?php echo Yii::t('App', 'Internationalization experiments') ? ?></p ?>
<?php endforeach ?>

would produce something like:

en: Internationalization experiments
it: Esperimenti con l'internazionalizzazione
pl: Eksperymenty z internacjonalizacją
Yii has a good and "natural" support for language plural rules. This is something everybody programming should take care of. For instance, see how easy it is to manage different plural forms for Polish:

<?php Yii::app()->language='pl' ?>  
 <ul>  
 <?php for($i=0; $i<=30; $i++): ?>  
 <li><?php echo Yii::t('App', '{n} file|{n} files', $i); ?></li>  
 <?php endfor ?>  
 </ul>  

To write a translation string like jeden plik|{n} pliki|{n} plików is enough to obtain

  • 0 plików
  • jeden plik
  • 2 pliki
  • 3 pliki
  • 4 pliki
  • 5 plików
  • 6 plików
  • ...
  • 10 plików
  • 11 plików
  • 12 plików
  • ...
  • 21 plików
  • 22 pliki
  • 23 pliki
  • 24 pliki
  • 25 plików
  • 26 plików
  • ...
Last but not least, if you want to access preferences set in the user's browser, you can follow the excellent example in Rethrown Exception.

Nessun commento:

Posta un commento