Painless Collapsible Divs In Drupal

15 Dec · by Tim Kamanin · 2 min read

It's almost midnight in my area, but I couldn't resist sharing this cool theming tip with you. Ok, so you want to create a cool collapsible div to hide some content on your page. What would you do? Write another javascript/jquery snippet and mess with callbacks, toggles, etc? Well, in Drupal this can be done even easier! Chaos tool suite (aka Ctools) comes to rescue! This module is a must have on any website, so don't worry about installing one more module to do a simple thing. And I'm 90% of you have it already installed.

Ok now to the process, let's collapse the div!

1) Put the content you want to see in a collapse field into the variable, let's call it $collapsed_content 2) And now the magic comes, use this theme function to output collapsible div:

print theme(
'handle' => 'Click me and you will see collapsed content', 
'content' => $collapsed_content, 
'collapsed' => TRUE

handle - stands for a clickable text which will collapse/uncollapse your div;

content - we put out content here, previously assigned to $collapsed_content variable;

collapsed - defines default state of a collapsible div, in our case it 's collapsed, if FALSE it's uncollapsed. Simple. That's all! Just two lines of code and you're set with a nice collapsible div.

Note for novices: you can put this code to your node template (for example, node.tpl.php file) OR to your custom module (custom_module.module file) OR to template.php file, on overall, to any place where you have a code which is responsible for the desired output. If you put this code into your custom module, don 't forget to add ctools dependency to your file or otherwise, your site may break if you accidentally uninstalled ctools.