0

I am developing a custom block that shows a different image URLs for different languages. Currently, I enabled English and French.

The code I am using is the following one.

function MODULENAME_theme($existing, $type, $theme, $path) {   
    $currentLangCode = \Drupal::service('language_manager')->getCurrentLanguage()->getId(); 
    $imageUrl = "";
    # If current language code is english
    if ($currentLangCode == "en") {
        $imageUrl = "English image url"
    } elseif ($currentLangCode == "fr") {
        $imageUrl = "French image url"
    }
    return [
       "modulename_block_template" => [
            "variables" => [
               "description" => [],
               "image" => $imageUrl,
               "current_language" => $currentLangCode
            ],
       ],
    ];
}

The problem is that the value for $currentLangCode is always 'en'.

What can I do to get the current language?

1

Data from hook_theme is cached, any logic decisions you make in it will only apply when the theme registry is rebuilt.

The point of variables is that they're passed in at the time the theme is called, not when the theme hook is declared.

For example hook_theme() should look like this:

MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'modulename_block_template' => [
      'variables' = [
        'description' => '',
        'image' => '',
        'current_language' => '',
      ],
    ],
  ];    
}

And you pass the variables in when you use it:

$currentLangCode = \Drupal::service('language_manager')->getCurrentLanguage()->getId(); 
$imageUrl = '';
# If current language code is english
if ($currentLangCode == "en") {
    $imageUrl = "English image url"
} elseif ($currentLangCode == "fr") {
    $imageUrl = "French image url"
}

$build = [
  '#theme' => 'modulename_block_template',
  '#description' => '...',
  '#image' => $imageUrl,
  '#current_language' => $currentLangCode,
];
| improve this answer | |
  • Thank you for this clarity. It started working after putting the language check code in Drupal\modulename\Plugin\Block\CustomBlock:build() method. – Dinesh Patra Mar 7 '18 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.