NEWS: Freelancer? Find something for yourself! Our list of Web Design Jobs »

I finally got around to implementing conditional content here on Snook.ca. I've wanted to do this since I moved to the new design just over a month and a half ago. The left sidebar has a number of elements like the projects I've worked, quick links, etc. As some people have noticed, if the article was particularly short, the comments would often overlap the rather lengthy content. I didn't want that.
With a little bit of late night development and some quick help from Larry (aka PhpNut, the lead developer of CakePHP), I've developed what I have dubbed "Elemental".
Elemental
Elemental consists of 2 parts: some new controller methods added to app_controller.php, and a new helper called Elemental.
In app_controller.php add:
function enableComponent($component, $params=null) { $name = Inflector::camelize($component); $found = loadComponent($name); if($found) { $cn = $name . 'Component'; $comp = new $cn($params); $comp->startup($this); $this->viewVars['elements'][$component] = true; } } function enableElement($element) { $this->viewVars['elements'][$element] = true; } function disableElement($element) { $this->viewVars['elements'][$element] = false; }
The methods enableElement and disableElement will turn on or off whether a particular element should be displayed in the view. The method enableComponent takes the extra step and conditionally loads a component and enables the related element that goes along with that.
To use the element in your view just do:
echo $elemental->load('projects');
In this particular example, it calls the projects.ctp element. This should work exactly like $this->renderElement but will only load if the element has been enabled using enableElement or enableComponent..
Here's the Elemental helper:
<?phpclass ElementalHelper extends Helper { function load($element, $params=array()) { $view =& ClassRegistry::getObject('view'); if(isset($view->viewVars['elements']) && isset($view->viewVars['elements'][$element]) && $view->viewVars['elements'][$element]) { return $view->renderElement($element, $params); } }}?>
Using it on Snook.ca
What I've done on Snook.ca then, is to break up the sidebar into a few different elements. All elements are enabled by default via the app_controller. Then, in my posts controller, I check the length of the body element and disable elements as the article gets shorter. Here are some examples:

Long article shows all elements
Medium-sized article shows just some of the elements
Short article shows no elements

I can now keep the sidebars light and avoid overlap or throw in some bonus material if the article is longer.
Discuss  |   Share  |  Sink
Comments Who Floated Related Links