Thursday, April 2, 2009

Internationalization PHP web sites using Smarty and gettext

What do we need?
  1. Gettext extention enabled in your PHP installation.
  2. Smarty gettext plugin, you can download it from sourceforge: http://sourceforge.net/projects/smarty-gettext/
Step I: Prepare your templates.
This is really easy step you jest need to put text you want to translate between {t}{/t},
example:
{t}translate this{/t}
OR
{t 1=$customers 2=$orders}There are %1 customers waiting for %2 orders.{/t}


The {t} block should be registered in the smarty. So the following code should be added while creating new smarty class.

require('Smarty.class.php');
require('smarty-gettext.php');

$this -> Smarty();
$this->register_block('t', 'smarty_translate');

smarty_translate is the method in the smarty gettext plugin which handles the translation.

Step II: Prepare input files for gettext
To do this you will need a tsmarty2c.php file from Smarty gettex plugin, and use it in console, here is an example:
php tsmarty2c.php PATH_TO_YOUR_TEMPLATE_DIR/template.tpl > template.c

php.exe is present in the installation path of PHP(C:\wamp\bin\php\php5.2.9) and it is a CLI(Command line interpreter) file. It will parse the tsmarty2c.php and generate the C file in the specified path.

Repeat this step for every file,
Step III: Prepare a .po file
To create a .po file you will need to use xgettext utility, for every .c file you created in the step II. Here is an example how to use it:
$ xgettext -o dictionary.po --join-existing --omit-header --no-location template.c

This file has two parts: header, and dictionary part, which you will need to edit.
msgid "translate this"
msgstr "here goes your translation"

Step IV: Convert .po file to .mo using msgfmt utility.

After translating everything, you will need to create the .mo file, here is example
$ msgfmt -o dictionary.mo dictionary.po

Step V: Prepare directory structure.
Gettext library has requires that files are stored in appropriate directory structure, here is an example:
/locale
/pl_PL
/LC_MESSAGES
smartybook.po
smartybook.mo

Step VI: Finale!
The final step is to tell your application to use translation that you have prepared. Below is an example of the PHP code you can use:
$language_code = 'pl_PL';
putenv("LANG=$language_code");
setlocale(LC_ALL, $language_code);
$domain = 'dictionary';
bindtextdomain($domain, './locale');
bind_textdomain_codeset( $domain, 'UTF-8');
textdomain($domain);

Need to set proper path to 'local' directory, used by a bindtextdomain function

No comments:

Post a Comment