5

I've tried to re-phrase my question in my head a million times, as there seem to be quite a number of approaches and solutions, but finally decided to ask it in a very general way:

What is the best way to localize variables in external javascript, such as help hints, tooltips, and such?

Currently I have my js pasted raw into PHP Code, in as many instances as there are languages on the site, and I'm switching the variable set based on:

<?php
  global $language;
  $lang = $language->language;
?>

but I strongly dislike having a gazillion of copies of same text throughout the site. This is good for testing, but for production I want just one javascript file which I could call with parameters, something like:

<script src="myscript.js?hl=<?php print $lang?>"><script>

3 Answers 3

7

Drupal has an in-built mechanism to handle this sort of thing, the Drupal.settings javascript variable you'll see in the source code for any Drupal site.

Used in conjunction with drupal_add_js() in your PHP code you can easily pass variables to javascript, which will be available in your custom script files.

For example in a custom module you could add a settings variable like this:

global $language;
$mySettings = array('language' => $language->language);

drupal_add_js(array('mymodule' => $mySettings), 'setting');

Then in your javascript file you can pick up that variable like this:

(function($) {
  $(function() {
    var language = Drupal.settings.mymodule.language;
    if (language == 'en') {
      // etc
    }
  });
})(jQuery);

Using this method your template code can be a lot cleaner and you don't need to worry about passing URL variables to the javascript file, or building up the javascript in PHP any more.

2
  • Wonderful concept, even though it requires writing a module ;-) Thanks a bunch! Commented Mar 2, 2012 at 21:30
  • @Artur No probs :) I'm pretty sure you could do this at the theme level, say in hook_preprocess_page() in the template.php file, so you wouldn't necessarily have to write a module
    – Clive
    Commented Mar 2, 2012 at 21:32
5

If you're talking localization, there's also a t() version of Javascript in the form of Drupal.t(), e.g.

   $("#div").text(Drupal.t('Mouseover tooltip'));

Your script will need to be added by drupal_add_js().

See http://drupal.the-aim.be/drupal-translate-jquery for a bit more on it.

1

Instead of passing the language in a setting or parsing the URL you can also use this code to get the actual language of the site:

var lang = $('html').attr('lang');

This works as all themes should render (at least) this info:

<html class="" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">

References:

JAVASCRIPT get current language!!!

Your Answer

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

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