0

In the project I am working on I have created a theme hook that renders a .tpl.php file:

/**
 * Implements hook_theme().
 */
function my_module_theme() {

  $theme['my_module_list'] = array(
    'variables' => array(
      '#markup' => array(),
    ),
    'path' => drupal_get_path('module', 'my_module'),
    'template' => 'templates/my_module_list',
  );

  return $theme;
}

Then I want some JS and CSS to be added only when this theme hook is used in the current page. Thus I implemented of theme_preprocess_hook() as such:

/**
 * Implements template_preprocess(). 
 */
function my_theme_preprocess_my_module_list(&$vars) {
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
  drupal_add_css(drupal_get_path('module', 'my_module') . '/css/my_module.css');
}

However it appears that the preprocess function is not called every time the hook is used resulting in CSS and JS not being added. What am I missing? Is it bad practice to add it there? And if yes where should I add it in order for it to be loaded only when necessary? I couldn't find any documentation that clarifies it and I've also seen it done other places.

Thanks a lot in advance :-)

2 Answers 2

1

I would add JS/CSS files inside the preprocess_page() function. If I don't want the CSS/JS files loading on some pages I will use an IF statement and check for a setting or if something exists etc, this will depend on the project.

1

Why don't you just use info files to add JS and CSS? My experience says it is the best way - it's stable, clean, easy to fint and tune. Also, it helps with aggregation and caching if you always have one set on all pages.

For conditionals - just use CSS and JS rules to find out if the page is one they need to be applied on. For example, test for specific class on <body> element, or script / style elements by their specific class or id.

1
  • 1
    I totally agree: Adding the same JavaScript and CSS files to all the pages makes possible to Drupal to aggregate and cache them.
    – avpaderno
    Commented Jun 18, 2015 at 10:39

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.