Translating panel custom widget

Hi,

I’ve built a custom widget in my panel and the website is multilingual.

How to translate the widget content (button label and other text …)?

I’ve tried with l::get()/ l::set() but l::get() doesn’t display anything in my widget.
However, l::get()/ l::set() works well for all my other front pages so my multilingual settings in my config file should be ok.

You might have a look at the logger plugin and how they solved it there.

Good luck

Thanks @bvdputte,

This plugin allow us to overwrite the default language by another language. The plugin is translated in english and if I need it to be in German, I can overwrite the english translation by a german one in the config file. But if the user switch his panel from german to english, the plugin stay in german.

So it doesn’t solve my multilingual problem :wink:

I am right @texnixe ?

The plugin uses a translate method, it tries to get the Panel language (if set), otherwise uses the language set in the config.

function translation($string) {
  $translation = c::get('logger.translation', false);
  if(!$translation) {
    $translations = require __DIR__ . DS . 'translations.php';
    $language = c::get('logger.language', c::get('panel.language'));
    if (! array_key_exists($language, $translations)) {
      $language = 'en';
    }
    $translation = $translations[$language];
  }
  if(array_key_exists($string, $translation)) {
    $string = $translation[$string];
  }
  return $string;
}

Of course, you have to provide translations for all your strings. User has options to provide own translations, though, for languages missing in the plugin.

Thanks @texnixe for these detailed explanation, as usual your help is very precious.

I’m going to study your code to apply the same method to my widget.

This is how I have adapted the @texnixe code to change the translation of my widget when the user switches the language in the panel in his user page options:

function translation( $string ) {
    
    $translations = require __DIR__ . DS . 'translations.php';
    // get the panel language selected by the user
    $language = $language_code = substr( site()->user()->language() , 0 , 2 );
    if ( array_key_exists( $language, $translations ) ):
        $language = $language_code = substr( site()->user()->language() , 0 , 2 );
    elseif( ! array_key_exists( $language, $translations ) ):
        $language = 'en';
    endif;
    $translation = $translations[$language];

    if (array_key_exists( $string , $translation ) ):
      $string = $translation[$string];
    endif;
    return $string;
  }