1

I use many template files in my modules via hook theme. In order to pass variable to JS files I use the method described here: https://www.drupal.org/node/304258 in the .tpl.php files:

$my_settings = array(
  'basePath' => $base_path,
  'animationEffect' => variable_get('effect', 'none')
);

drupal_add_js(array('myModule' => $my_settings), 'setting');

and then in the .js files:

var basePath = Drupal.settings.myModule.basePath;
var effect = Drupal.settings.myModule.animationEffect;

For the first time (it seems) I'm trying to pass variables to JS from .tpl files located in my theme folder. Suppose I have a content type called 'cars', I craete a page-cars.tpl.php template file in my theme folder which automatically applies to all car pages. But in these tpl files I can't pass variables to JS using the method described above. I tried switching 'myModule' to 'myTheme' but Drupal won't recognize it as a defined setting

As per Clive's instructions I added to the my_theme_preprocess_content_type(&$variables) function and it works! (thanks Clive)

  • Which part of the docs you read said you should put a call to drupal_add_js() in a template file? Or have you assumed? I only ask because if there are official docs telling you to use drupal_add_js() in a template file, they need to be changed ASAP. That code should be in a preprocess function, never a template file. – Clive Feb 5 '15 at 13:48
  • Been doing it this way for years now Clive... Probably a bad habit I developed unintentionally. – Liam Arbel Feb 5 '15 at 14:15
  • Bad indeed! It'll probably work in a lot of cases, but it breaks caching and can have unwanted effects (possibly like you're experiencing now). Try moving the logic to a preprocess function just to make sure that's not the problem – Clive Feb 5 '15 at 14:43
0

Take a look at the variable_set function. If my memory is correct, I used this to move variables between PHP and java script.

  • I don't think thats right, this sets drupal variables like site_name in the variables table and doesn't necessarily expose them to JS. – bloke_zero Feb 6 '15 at 9:57

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.