Reuseable page elements with renderElement()
Posted on | November 18, 2008 | 2 Comments
When you find yourself repeating HTML codes in pages of your website or web application, this is a useful function for factoring your codes. Whenever I make changes to my codes, I will make it a point to refactorize as much as possible. It keeps the codes managable. But over factorizing will make it hard for the next programmer taking over the maintenance of the application.
renderElement() is just one of the ways to factorizing your codes. In Cakephp, you can make use of custom helpers, tempalates, plugins, components to make your code reuseable and tidy.
renderElement() is defined in the controller class. Therefore you do not need to include helper to use it.
In your views, (.ctp files), you will call with
<?php echo $this->renderElement('addthis',
array(
'url' => $html->url(array('action' => 'view', $feature['Feature']['id']), true),
'title' => $feature['Feature']['title'])); ?>
The first argument is the name of the element to be included. In this example, the element name is addthis. You will find addthis.ctp in the /views/elements. The second argument is an array of variables to be passed to the element. The key of each array item is the name of the variable. The array items will be translated to ${name}. which is $url, and $title when referencing in addthis.ctp.
This is how you can use the variables in your element.
<?php
!isset($url)? $url = 'default' : null;
!isset($title)? $title = 'default' : null;
echo $html->image($url, array('title' => $title));
?>
Comments
2 Responses to “Reuseable page elements with renderElement()”
Leave a Reply





















November 18th, 2008 @ 5:35 am
And if you want to structure your elements even further, just use directories:
/views/elements/posts/head.ctp
/views/element/posts/footer.ctp
/views/elements/index/navigation.ctp
You can just render them like this:
$this->render(‘posts/head’);
It’s trivial, but maybe helpful
November 18th, 2008 @ 11:51 am
Yes, very useful when the website is big and requires more organization.
Thanks to Dirk for bringing it up.