Skip to content

Kirby 3.6.6

Flexible language variables

The "standard" way to store language variables in Kirby is to define an array of language variables in the language file itself, e.g. /site/languages/de.php.

/site/languages/de.php
<?php

return [
  'code' => 'de',
  'default' => false,
  'direction' => 'ltr',
  'locale' => 'de_DE',
  'name' => 'Deutsch',
  'translations' => [
    'change' => 'Ändern',
    'confirm' => 'OK',
    'copy' => 'Kopieren',
    'create' => 'Erstellen'
  ]
];

This is fine if you only need a small set of fixed variables. If this is not flexible enough for your use case, you can replace the array of key/value pairs with a link to a file or a function that returns an array.

For example, if you want to store your variables in a yaml file instead, you can read the file into an array:

/site/languages/de.php
<?php

return [
  'code' => 'de',
  'default' => false,
  'direction' => 'ltr',
  'locale' => 'de_DE',
  'name' => 'Deutsch',
  'translations' => Yaml::decode(F::read(kirby()->root('languages').'/vars/de.yml'))
];

And then in /vars/de.yml, define your variables:

/site/languages/vars/de.yml
change: Ändern
confirm: OK
copy: Kopieren
create: Erstellen

Or, you can use a function that returns the variables array:

/site/languages/de.php
<?php

return [
  'code' => 'de',
  'default' => false,
  'direction' => 'ltr',
  'locale' => 'de_DE',
  'name' => 'Deutsch',
  'translations' => getVariables('de')
];

And in a plugin, define a function that returns your variables:

/site/plugins/variables/index.php
function getVariables($lang = null) {
   /* here you can fetch your variables from anywhere:
   ** a spreadsheet, a .csv file, or
   ** from a structure field that you can edit in the Panel
   */
   $translations = [];
   return $translations;
}

As you can see, you can get pretty flexible with this to make it work with the requirements of your multi-language project.