I have a custom module that i've created and I have set the theme template like this:

 * Implemtnation of hook_theme()
function custom_slider_theme($existing, $type, $theme, $path) {
    return array(
        'custom_slider' => array(
            'variables' => array('nodes' => NULL),
            'template' => 'custom_slider',

This is all working fine.

What I can't find is how to load a css file for that template so when custom_slider.tpl.php is loaded the relevent css file is loaded. I don't need that css loaded on every page. I would rather call drupal_add_css() only when it's needed.

I used below approach, but it's not working.

function ModuleName_preprocess_TemplateName(&$vars) {
      drupal_add_css(drupal_get_path('module', 'custom_slider') . '/file.css');

Also I added

'preprocess functions' =>array('ModuleName_preprocess_TemplateName'),

in hook_theme, where I defined my templates, kindly suggest the right way to do it.

Any help with this is very much appreciated.

2 Answers 2


Drupal will automatically call hook_preprocess_[template] for each template defined in hook_theme.



Should be called by default. If not, then clear your cache to be sure the preprocess function is registered.

Fun fact is preprocess functions are called for theme functions as well, e.g theme_item_list calls hook_preprocess_item_list prior to rendering.

  • I have 4 templates and 4 css files.. css1 belongs to template1, css2 belongfs to template2 and so on..I am using preprocess function so that css1 should only effect to template1 and so on.. MODULE_preprocess_template1(&$variables){drupal_add_css('css1')}and MODULE_preprocess_template2(&$variables){drupal_add_css('css2')} Is this the right way to apply css on particular template file, so when template1 is invoked, only css1 classes apply on it, not css2 classes. P.S. css1 and css2 contains same classes name. Aug 4, 2015 at 6:30
function ModuleName_preprocess_TemplateName(&$vars) {
      drupal_add_css(drupal_get_path('module', 'custom_slider') . '/file.css');

This function works perfectly, just ensure that the css file is in the same folder as the .tpl.php and .module files

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.