11

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: ƒ}
locale:{}
stringReplace:ƒ (str, args, keys)
t:ƒ (str, args, options)
theme:ƒ (func)
throwError:ƒ (error)
url:ƒ (path)
views:{instances: {…}, ajaxView: ƒ}
__proto__:Object

2 Answers 2

5

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:

console.log(drupalSettings.language);

Edit

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

frontend:
  dependencies:
    - core/drupalSettings
2
  • See answer below, this is already provided by Drupal core, so this answer is out of date and adding data we don't need Commented Dec 2, 2022 at 15:27
  • Thank you for the hint! Probably my answer from 2017 is a little bit outdated ;-) Good to know that there is a better solution. Commented Dec 5, 2022 at 19:09
38

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

var langCode = drupalSettings.path.currentLanguage;
1
  • 3
    This is such a better answer. Commented Jan 7, 2020 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.