3

Inside my custom views template, views-view-myview.tpl.php, I have a variable ("$myvar"), which I need to pass to a custom javascript function. Here is how I am currently doing it:

A. json-encode $myvar

<?php
$my_json_var = json_encode($myvar);
?>

B. Pass the variable as an argument to my custom function, on page load

<script>
Drupal.behaviors.mystuff = function (context) {
  my_js_function(<?php print $my_json_var; ?>); 
});
</script>

I am noticing that Drupal developers generally pass variables to javascript using Drupal.settings, and I am wondering whether I should switch and use Drupal.settings instead.

Question: Is there any disadvantage of doing things my way, as described above? Is there any reason it would be better to switch to Drupal.settings. Note: $myvar is relatively large, say 100k.

Thanks very much

1 Answer 1

4

The advantage of having in Drupal.settings is the values can be globally accessed across the JavaScript functions. In your case the function "my_js_function" only can access it because of its scope. It is based on the need and if you feel it is unnecessary to have it in settings then you can go with your method.

But best practice is to use Drupal settings. This method will never fail you.

2
  • 3
    I agree with @Dinesh, if you need these variables in multiple functions, you will have to pass them each time. And if one day you need to add one more variable, or delete one from the JSON, you will have to edit all functions call instead of just editing Drupal.settings once. DRY as much as possible
    – Mika A.
    Oct 30, 2012 at 7:15
  • Thank you both very much. Exactly what I needed to know.
    – user606696
    Oct 30, 2012 at 23:27

Your Answer

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

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