Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter: How to 'highlight' the link of the page the user is currently on?

Fairly new to CodeIgniter, still grasping the MVC approach. I'm just wondering what's the best way to solve this:

I got my navigation bar highlighting the currently active link like so:

<a href="index.hml" id="active">Index</a>
<a href="blog.hml">Blog</a>

Now, when I go to blog.html I want id="active" to shift accordingly. Usually I'd assign a variable to each link and then set it's value to 'id="active'. Somehow I don't think that's the best way. Any thoughts?

Update (12. Sept 2012) Since asking this I've moved on to Kohana and expanded a module created entirely for this purpose. Now, all I need to do is specify my menu items in a config array and the highlighting happens automagically. The module is here.

like image 928
anroots Avatar asked Jul 28 '10 20:07

anroots


2 Answers

Non-specific to CI this is just logical checks agains the current page name.

When you get the page name in CI such as

$pageName = 'blog.html';

Then you can do the following

<a href="index.html" <?php echo $pageName == 'index.html' ? 'id="active"' : ''; ?>>Index</a>
<a href="blog.html" <?php echo $pageName == 'blog.html' ? 'id="active"' : ''; ?>>Blog</a>
like image 105
Paul Dragoonis Avatar answered Sep 30 '22 07:09

Paul Dragoonis


First of all you should not be using id for that kind of things, id is to give a unique identification number to each DOM element on the page, for what, we best use a class.

Code Igniter provides a lot of helpers and classes that become part our tools, probably you have heard of "URL Segments" before.

$this->uri->segment(n)

Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this:

http://example.com/index.php/news/local/metro/crime_is_up

The segment numbers would be this:

  1. news
  2. local
  3. metro
  4. crime_is_up

http://codeigniter.com/user_guide/libraries/uri.html

you can use that to retrieve the current URL segment that represents the Active Page you are actually displaying on the browser.

like image 21
Germán Rodríguez Avatar answered Sep 30 '22 07:09

Germán Rodríguez