As we all know well, Moodle is a multilingual system which, depending on the wishes of the user, can perfectly support many languages. As a rule, when developing a new plugin, there are no big difficulties for the introduction of a language translator, but there are a few nuances about which we will talk about.

The lang/en/plagin_name.php folder is responsible for the language set, which can be found in the root of any plugin. This folder contains files with an array of strings for each of the languages.

Let us consider a simple example of a sequence of actions for adding a new string to our plugin.

Add a new entry with the required line to the lang file. (lang/en/plagin_name.php)

$string['pluginname']      = 'Edwiser RemUI';
$string['fullscreen'] = 'Full screen';
$string['closefullscreen'] = 'Close full screen';

Now you can use the string anywhere in our plugin.

Add multi lang string on PHP

$text = get_string('string_name',  'plagin_name');

Add multi lang string on {{ mustache }} template

<p>{{#str}}string_name, plagin_name{{/str}}</p>

Add multi lang string on javascript

Here you need to clarify that you can use the translator directly in JS only if the script is used as an AMD module. Connecting AMD modules is a topic for a separate article. You can read about it here https://docs.moodle.org/dev/Javascript_Modules

To connect a multi-lang string in our source module, we include the core AMD module core/str.

define(['jquery', 'core/str', 'core/notification'], function($, str, notification) {
// start retrieving the localized string; store the promise that some time in the future the string will be there.
 var translation = str.get_strings([
     {key: 'string_name', component: 'plagin_name'},
 ]);
  // as soon as the string is retrieved, i.e. the promise has been fulfilled,
  // edit the text of a UI element so that it then is the localized string
  // Note: $.when can be used with an arbitrary number of promised things
 $.when(translation).done(function() {
   $('someUIElementSelector').text(M.util.get_string('string_name', 'plagin_name'));
 }).fail(notification.exception);
});

After adding new lines to the translator, don’t forget to clear your cache in order for the changes to take effect.

More information

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.