Milk Admin

Lang Class Documentation

This documentation provides a detailed overview of the Lang class and its functions.

Introduction

The Lang class manages string translations within the system. It allows setting and retrieving translations for different areas and loading translation files.

Language files are loaded from the lang folder. The name of the file to load is saved in the configuration

$conf['lang'] = 'en';

The lang class can also be used to override language settings within a module. If a module's translation also modifies translations of other modules, you can limit the scope of intervention. The area is defined by the page query string ($_REQUEST['page']) in the page call

Usage

The lang class, like the Sanitize class, is not used directly but generally through the following functions

Print a translated string
 _pt('Hello World');
Print a translated string with variables
printf(_rt('Hello %s'), 'World');

If you need to return the string in a variable, you can use sprintf

$var = sprintf(_rt('Hello %s'), 'World');
For a complete list of functions that handle sanitization and translation, see the documentation for Sanitize

Functions

set(string $string, string $translation, $area = 'all')

Set a string and its translation.

Lang::set('hello', 'hello', 'greetings');

get(string $string, $area = 'all')

Gets the translation of a string.

$translation = Lang::get('hello', 'greetings');
echo $translation; // Output: hello

loadPhpFile(string $file, $area = 'all')

Load a PHP translation file.

$success = Lang::loadPhpFile('path/to/translations.php', 'greetings');

Translation files are PHP files that return an array where keys are English strings and values are translations:

<?php
// translations.php
return [
    "Hello World" => "Ciao Mondo",
    "Save" => "Salva",
    "Cancel" => "Annulla",
];

Javascript translation

Translation can also be done in javascript with __(key, params = {})

The translation uses the same PHP files, without the areas. You must wait until the translation file has loaded, otherwise the original text will be returned.

waitForTranslations().then(() => {
    alert(__('Hello %s', ['World']));
});

waitForTranslations() waits for translations to load, but if the translations aren't supposed to appear immediately, but rather later, it can be assumed that the loading has already been successful. If the translations haven't been loaded yet, the original text is still returned.

Loading...