Adding variables to localised (i18n) strings in CakePHP

The localisation (i18n) features of CakePhp are powerful and flexible.  One of the common tasks required when localising text is to provide variables within the text such as numbers or indeed other translated chunks of text that operate independently from the main translation.

In step sprintf() and printf().  Both of these functions are very similar, they essentially take a string input with some replacement holders (with a syntax like %d for integers or %s for strings) and then replace them with the variables you specify.  sprintf() is different to printf() only in that the prior returns a variable that can be used whereas printf() simply returns the output to the console.

So how to add variables to localised (i18n) strings in CakePHP?  Using a combination of the inbuilt __() and __n() functions and wrapping them with these new functions, for example:

printf(__("Hello %s welcome to my blog", true), $name));

This will replace the %s (which is a “string” replacement holder remember) with the variable $name,  remember printf() is purely an output function it does not return a variable, for that you need sprintf() for example:

$welcomeNote = sprintf(__("Hello %s welcome to my blog, you are visitor number %d today", true), $name, $visitorcount));

The above example also demonstrates multi variable replacement.

NB:  remember to add the second parameter  “true” to the __()/__n() function to return this as a variable as well, otherwise like printf() it will simply output the string at runtime.

A full list description of the sprintf() and printf() functions is available on the php website, but for adding variables to localised strings in cakephp use the method described above.

Bookmark and Share

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

[...] Adding variables to localised (i18n) strings in CakePHP | HonkBlog|TechNotes So simple you'd almost forget it's possible to do it this way. (tags: cake php i18n variables howto) [...]

it’s really useful, thank you.

Thanks .It worked for me.I just want to know that i am displaying my string like:
$resourcename=’saru’;
$date=’03/03/2011′;
$value=’11:00′;
$businessloaction=’chd’;
$bname=’fortis’;
$bphone=’432423432434′;
$Confirmationmessage_eng =sprintf(__(“Confirmation: You have an appointment with %s in %s on %s at %s. Address is %s. Change it with your PIN online or call %s, Mo-Thu 8-16, Fri 9-15. To cancel reply with ‘Cancel’ before the day of appointment”, true), $resourcename,$bname,$date,$value, $businessloaction,$bphone)

Here if i am using the %d for date or time or phone then it is not displaying correct.
My 2nd question is that should we have to user only %s for all the variables which are of type string in the main string?

Leave a comment

(required)

(required)