In a site navigation bar, I have some logic that determines which page the user is currently viewing, and gives that menu-item an .active class.
The code I came up with does work, though it doesn’t feel very elegant. Can you think of a way to do this better? How could I move the logic out of the view and into the controller? How can I stop repeating myself?
The controller:
<?php
class Pages extends CI_Controller {
public function view ($page = 'home') {
if (!file_exists('application/views/pages/'.$page.'.php'))
show_404();
$data['active'] = $page;
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
}
?>
The view:
<ul class="nav">
<li class="<?php echo($active=='home')?'active':''; ?>"><a href="./">blog</a></li>
<li class="<?php echo($active=='about')?'active':''; ?>"><a href="about">about</a></li>
<li class="<?php echo($active=='projects')?'active':''; ?>"><a href="projects">projects</a></li>
<li class="<?php echo($active=='lab')?'active':''; ?>"><a href="lab">lab</a></li>
<li class="<?php echo($active=='contact')?'active':''; ?>"><a href="contact">contact</a></li>
</ul>
Maybe more elegant ?
This way depend of complexity of your uris.