Drupal 7 get current language in JavaScript

Posted on 06/07/2016

By default there is no way to access the language through JS in Drupal 7. You could of course read the lang attribute of the <html> tag, but that is far from being an optimal solution.

Luckily, this is pretty easy to achieve through a custom module. Here's what you need to do:

  1. Hook into every page load - both front and back end.
  2. Get the current language code.
  3. Make it available as JS variable.

This code would go in YOUR_MODULE.module file:

  1. /**
  2.  * Implements hook_page_alter().
  3.  */
  4. function YOUR_MODULE_page_alter(&$page) {
  5.   global $language;
  6.   // Add current language to the JS settings.
  7.   drupal_add_js(array(
  8.       'YOUR_MODULE' => array(
  9.         'language' => $language->language,
  10.       ),
  11.     ),
  12.     array('type' => 'setting')
  13.   );
  14. }

You can then access this in JS the following way:

  1. Drupal.settings.YOUR_MODULE.language

Drupal 8 already includes this and you can use it the following way:

  1. drupalSettings.path.currentLanguage;