1

I'd like to use the $node object in JavaScript, preferably Drupal's DOM. Is there a recommended way to do this in Drupal?

1 Answer 1

1

There are several ways to go about this. The most straightforward is use template_preprocess_node , drupal_add_js, and drupal_json_encode.

Something like this:

function mytheme_preprocess_node (&$variables)
{
  $node = $variables['node'];

  drupal_add_js(array(
    'mytheme' => array(
      'node' => $node,
    )
  ), 'setting');
}

The node will then be JSON encoded as Drupal.settings.mytheme.node. The above is untested, but will be a decent starting point. Keep in mind that if you have multiple nodes on a page, then this will get called multiple times. You would need to add some logic to handle these cases.

If you do this as part of themeing, rather than a module via the Node API, then all modules that alter the $node will have run at that point, so all data should be there. Personally, I would only add the data that I need. $node can get pretty big, so adding all of it would be a lot of JS on a page.

5
  • 2
    The drupal_json_encode() shouldn't be necessary, Drupal will automatically convert the whole settings array to the javascript pendant.
    – Berdir
    Nov 5, 2011 at 11:27
  • 2
    Also, keep in mind that this will expose the complete node object to any visitor and it does very likely include confidential information like the mail address from the author of that node. It also makes the page response bigger, especially if you have large node objects with many fields. I strongly suggest you only add the properties you actually want to use in JS.
    – Berdir
    Nov 5, 2011 at 11:28
  • Thank you MPD for the solution above! I'm totally rolling my codes with it now!
    – Logi
    Nov 6, 2011 at 1:42
  • Berdir, thanks for the append too, it's useful reminder!
    – Logi
    Nov 6, 2011 at 1:45
  • Editited to reflect the comment from @Berdir. I always forget that...
    – mpdonadio
    Nov 6, 2011 at 17:07

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.