How can I get the language code or name from the Drupal javascript object in a js script ??

I know I can get language using this in php:

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

But I need to have the language in my scripts.

All i got so far is the Drupal Jquery variable

Var d = Drupal;

Which when printed looks like this.

{behaviors: {…}, locale: {…}, throwError: ƒ, attachBehaviors: ƒ, detachBehaviors: ƒ, …}
Ajax:ƒ (base, element, element_settings)
AjaxCommands:ƒ ()
AjaxError:ƒ (xmlhttp, uri, customMessage)
ProgressBar:ƒ (id, updateCallback, method, errorCallback)
Views:{parseQueryString: ƒ, parseViewArgs: ƒ, pathPortion: ƒ, getPath: ƒ}
ajax:ƒ (settings)
attachBehaviors:ƒ (context, settings)
behaviors:{autologout: {…}, drupalDisplace: {…}, responsiveImageAJAX: {…}, AJAX: {…}, activeLinks: {…}, …}
checkPlain:ƒ (str)
debounce:ƒ (func, wait, immediate)
detachBehaviors:ƒ (context, settings, trigger)
dialog:ƒ (element, options)
displace:ƒ displace(broadcast)
encodePath:ƒ (item)
formatPlural:ƒ (count, singular, plural, args, options)
formatString:ƒ (str, args)
history:{fetchTimestamps: ƒ, getLastRead: ƒ, markAsRead: ƒ, needsServerCheck: ƒ}
stringReplace:ƒ (str, args, keys)
t:ƒ (str, args, options)
theme:ƒ (func)
throwError:ƒ (error)
url:ƒ (path)
views:{instances: {…}, ajaxView: ƒ}

You can add whatever you want to the javascript via your THEMENAME.theme:

function THEMENAME_preprocess_page(array &$variables) {
    $variables['#attached']['drupalSettings']['language'] = $language;

After that, you can call it in javascript:



You need to enable drupalSettings as a dependency in your THEMENAME.libraries.yml:

    - core/drupalSettings

In pages with the core/drupalSettings library included, it seems to be pretty reliably available through the path:

var langCode = drupalSettings.path.currentLanguage;
  • This is such a better answer.
    – Patrick
    Jan 7 '20 at 21:55

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.