0
votes

I'm themeing a drupal site using display suite - all current versions. As you may realise, in drupal there are many ways to achieve an equivalent result. I have created a number of custom layouts in display suite. Now I want to add jquery to some of those layouts so that the jquery only loads when those layouts are displayed (as opposed to making the same jquery file load on every page in the theme).

Sure I can use something like drupal_add_js() or $form#attached etc. But what's wrong with adding a tag in my template file? What is the 'Display Suite method' for doing this - I have to believe they (Display Suite team) have already thought of this...

Thanks.

1

1 Answers

0
votes

One way to accomplish this is through hook_ds_pre_render_alter(), e.g:

/**
 * Implements hook_ds_pre_render_alter();
 * Add custom JavaScript.
 */
function MYMODULE_ds_pre_render_alter(&$layout_render_array, $context, &$vars) {
  if($vars['type'] === 'MY_NODE_TYPE' && $vars['view_mode'] === 'full') {
    drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/js/my_js_file.js');
  }
}

Adding the JavaScript through #attached would be preferable as it seems cleaner and is more in line with the approach taken in Drupal 8, however I couldn't find a way to do this. Display Suite seems to override hook_node_view() and adding #attached in to an implementation of ds_pre_render_alter() didn't get me anywhere. Declaring a .js file in a custom DS .inc layout file is also unfortunately not supported.

Implementing drupal_add_js() directly in a .tpl.php template file might not work as expected and seems to not be 'best practice' (see https://drupal.stackexchange.com/questions/20520/drupal-add-js-in-html-template-file).

Interestingly though in Drupal 8 drupal_add_js() is being removed entirely in favour of #attached and it will be possible to add JavaScript directly in templates, see https://www.drupal.org/theme-guide/8/assets).