Wednesday, June 11, 2014

Writing a module for an entire page in Drupal

If like me you like to modularise your programs you might like to create a page of your website that corresponds to a single module. I currently have modules for biography, browse and experiments. What doesn't satisfy me about Drupal is the fact that "content management" usually means writing stories in HTML and displaying them on pages. I see a CMS as a shell within which to develop interactive content with more bells and whistles. Hence I tend to write one module for each major page.

First there is the problem that Drupal considers modules as extensions to every page, and will load your javascript and css throughout the site. One way to avoid this is not to add them to the module.info file. Don't write stylesheets[all][] = css/my_module.css, or scripts[all][] = js/my_module.js, or that will get added on every page. Instead, load them dynamically whenever the module gets loaded, and then control when that happens. In your my_module.module file define the following hook:

So only when the url contains the string "my_module" (please substitute the name of your module) will the js and css get loaded.

The next problem is how to make it call the module so that the url http://site.com/subdir/my_module will actually display that page. The secret is another callback in mymodule.module:

So now the path http://site.com/subdir/my_module is a page, and any attempt to access it calls my_module_all, which can do anything you like and should just return some html. That, I believe, is all there is to it.