I was looking for a flexible way to generate different sidebars in different pages. The goal is to pass custom links to each sidebar. The template libraries seemed overkill for my application so I developed an easy solution. I’m not certain if it’s the best solution. My question is what do you think? Your advice is immensely appreciated!
1. In your controller add a private function that loads your sidebar view:
/**
* The function has 2 arguments.
* $title is the sidebar widget title.
* $widget will contain an array of links to be added in the sidebar widget.
*/
private function sidebar($title, $widget)
{
$widget['title'] = $title;
$this->load->view('includes/sidebar', $widget);
}
2. In the controller functions that you want to load a custom sidebar, call the private function sidebar() and pass desired sidebar data into it.
Below is a controller function named edit used to edit posts. In the example I need to load a sidebar with options to view and delete the post I’m on:
function edit($post_id = '')
{
//your code, form validation, etc...
//Prepare sidebar widget links
//Array key is link url, array value is link name
$widget['links'] = array (
'posts/single/' . $post_id => 'View post',
'posts/remove/' . $post_id => 'Remove post'
);
$this->sidebar('Options', $widget); //load sidebar
}
3. Finally the sidebar view displaying custom data passed from the controller:
<div id="sidebar">
<ul>
<li class="widget">
<div class="label"><?php echo $title; ?></div>
<ul>
<?php foreach ($links as $link => $value): ?>
<li><?php echo anchor($link, $value); ?></li>
<?php endforeach; ?>
</ul>
</li>
</ul>
</div>
Conclusion
Add the following code to any controller function for custom sidebar title and links:
$widget['links'] = array (
'controller/function' => 'Link Name 1',
'controller/function' => 'Link Name 2',
'controller/function' => 'Link Name 3'
);
$this->sidebar('Widget Title', $widget);
I think that gets it done. I’m not an expert in CodeIgniter, but I can tell you that’s just fine. One thing you should always make sure is to validate the data passed to a function. In this case:
Another way to do it is just to pass the links to the template (not the sidebar template, but your main template:
And in the template you load the sidebar template and pass it the data:
This is just another option. But what you did is just fine.