How to translate static text strings containing variables?


I read the documentation on static string translation, but could not find anything about how to translate static strings containing a variable or translations involving either the singular or plural form of a word.

Therefore I would like to ask if these use cases are supported by Kirby.



You may want to checkout this plugin for a solution:

This seems to be a great plugin, but it is too narrow in scope as it only targets dates.

What I was looking for is something like this:

Translation involving a variable:

$car = "Mercedes";
translate("I am driving a %s", $car);

Translation involving a variable and either the singular or plural form:

$num = 2;
translate("There is %d blog post", "There are $d blog posts", $num);



I didn’t mean to say you should use this plugin, but wanted to point out this plugin as an example of handling strings with variables in Kirby.

in your language files:

l::set('car', 'I am driving a {{1}}');
l::set('blogposts.singular', 'There is 1 blog post');
l::set('blogposts.plural', 'There are {{1}} blog posts');
l::set('welcome', 'Hello {{1}}, your total visits: {{2}}');

as a plugin:

function translate($key, $replacements = array()) {
  $string = l::get($key);
  if(is_string($replacements)) $replacements = array($replacements);
  foreach($replacements as $placeholder => $replace) {
    $string = str_ireplace('{{' . $placeholder . '}}', $replace, $string);
  return $string;

using it:

echo translate('car', 'Mercedes');
e($num > 1, translate('blogposts.plural', $num),  translate('blogposts.singular'));
echo translate('welcome', array($name, $visits));

As you can see in my plugin (the one @texnixe pointed out), it gets much more complicated if you want to figure out singular/plurals and so on automatically. Easier to define both versions already as separate language strings.

1 Like