How to build a dynamic and maintainable navigation

In this article we will see how we can create a navigation that is able to highlight the current page in menu items like this example. As you can see, the style of the menu item applied to the page displayed is different from other entries.
To do this in a stylish way and most important, in maintainable way, we must build the navigation “dynamically“, ie through the programming with PHP. Although the steps are explained in depth, it requires medium knowledge of the language to follow and understand the topic of the article.

We prepare the pages (X)HTML

We start preparing the pages. Nothing complex, an element in the left navigation and one for the content in the right.
We start with the index.php page:

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html;  charset=utf-8">
    <link href="style.css" rel="stylesheet"  type="text/css" />
</head>
<body>
    <div id="navigation">

    </div>

    <div id="content">
        <h1>Page home</h1>
    </div>
</body>
</html>

As I said nothing special. You can now save this page as profile.php, contact.php, newsletter.php, taking care to change the title contained in h1 tags.

The stylesheet

Now, let’s pass to the stylesheet (style.css appointed by me) and as you can see I’ve already linked to the document in the head pages just made.

body{
    font-family: Verdana, Geneva,  Arial, Helvetica, sans-serif;
    font-size: 14px;
}

#navigation{
    width: 200px;
    padding: 20px;
    float: left;
    padding-top: 100px;
}

a:link,a:visited{
    text-decoration: none;
}

li{
    list-style-type: none;
    margin-bottom: 5px;
}

li.active{
    color:gray;
    list-style-type: disc;
}

Even the stylesheet is pretty simple. In the list elements eliminate the marker and then show it instead in elements with active class. This class is the one that we will associate to the menu item on the displayed page.

Make navigation maintainable

Since, as mentioned above, the navigation will be created by PHP scripts, it is important to keep out of the code elements that may require additions or changes. This small effort on the altar of maintainability would make us very happy in the future.
Therefore it will creates the navigation.txt file in which we will write the menu items and their links separated by “:”.

home:index.php
profile:profile.php
contacts:contact.php
newsletter:newsletter.php

Develop the function ”Navigation()”

Now creates the file funtions.php. I have chosen this name because we used not only to generate the navigation, but also to bring along a number of other functions to be used in our pages.
Begin to develop the function. What we will do is:

  • Decide in which page we are (index.php, contact.php,…);
  • Read the content of the file navigation.txt and process to dispose the items and related links;
  • Check if the link corresponds to the name of the page that appears, in that case we must add the active class;

But first there must be explained what is an array because it will be very useful.
The array is a type of variable that contains a collection of values associated with a key. Said this way it seems very complicated, so I’ll make a practical example.

Declare the array $colors

$colors =  array("red","green","yellow");

Now, the variable

$colors[0]

return red (the first array element has key 0), while

$colors[2]

return yellow (like saying that the key “2″ has value “yellow”)

An array can also be associative:

$person  = array("name" => "Maurizio", "surname" => "Tarchini");

In this case the key is not numerous but inserted explicitly, then:

$person['name']

returns the name of Maurizio.

I stop here. In reality, an array can achieve a level of enormous complexity, for example I can insert an array value as another array. We discuss this case of multidimensional arrays. We could also say that there are other ways to exploit and manipulate arrays, but now we do not care.

We begin now to declare the function Navigation () and to procure the name of the current page.

<?php
function  Navigation()
{
   $activePage = basename($_SERVER['PHP_SELF']);

The $ _SERVER is an associative array created automatically, available always and everywhere (technically called a superglobal array) that contains various information regarding the server. The key PHP_SELF returns the path/filename of the displayed page.

Through the function basename () we will “purify” the result from the path obtaining what we want: the name of the page that appears, that we will put in the variable $activePage.
Now we can read and process the contents of the file navigation.txt. The best way is to use the function file().

$rows  = file('navigation.txt');

This function reads the contents of the file passed as an argument and returns an array based on the lines of this document (each line a value).

For example, $rows[0] will contain home:index.php

At this point what we have to do is:

  • For each value of the array $rows “break” the string to the sign “:” so we will get the name to display on the menu and the link to which it should point;
  • Check if the name of the page is the one of the page displayed (if so,you shall add the active class, if not, than print the link);

To do this we will use a foreach loop, this is a cycle specifically designed to “browse” arrays.

echo  '<ul>';
foreach($rows as $row)
{
}

Before starting this cycle print the opening tag of the list.
In summary, the syntax of foreach means this:
“Run the code contained in braces (which have not yet written) many times as are the values of $rows. For each cycle you take the variable $row one of the values of $rows.”
So in the first step will equal $row to $rows[0], in the second step will equal $row to $rows[1], and so on.

Now we have to “break” on “:” the string (name link). Use the explode() function that does just that. Indeed explode() takes two arguments: the separator (in our case “:”) and the string. Returns an array whose values are the parts of broken string.
For example in the first step the situation is this:

$result  = explode(":" , "home:index.php");

Then $result[0] will contain home and $result[1] will contain index.php

So our loop looks like:

$nav = explode(":", $row);
$page  = trim($nav[0]);
$link = trim($nav[1]);
if($link == $activePage)
{
    echo '<li>' . $page . '</li>';
}
else
{
    echo '<li><a href="' . $link . '">' . $page .  '</a></li>';
}
}
echo '</ul>';

Enhance value of $page with the first line and $link to the second. I apply the function trim() to eliminate any spaces before and after.
And finally, let’s see if it is the page currently displayed by the control structure if/else.
If it is, I will print the tag <li> with active class, otherwise it will print “smooth” but making sure to declare the link.
Once the cycle ends (ie when printed all the navigation), close the ul tag.

And here’s the complete function:

<?php
function  Navigation()
{
    $activePage = basename($_SERVER['PHP_SELF']);
    $rows = file('navigation.txt');
    echo '<ul>';
    foreach($rows as $row)
    {
        $nav = explode(":", $row);
        $page = trim($nav[0]);
        $link = trim($nav[1]);
        if($link == $activePage)
        {
            echo '<li  class="active">' . $page . '</li>';
        }
        else
        {
            echo '<li><a href="' . $link .  '">' . $page . '</a></li>';
        }
    }
    echo '</ul>';
}
?>

Now we have to include the file functions.php on all pages and call the function Navigation(), as follows:

<div  id="navigation">
    <?php
        include 'functions.php';
        Navigation();
    ?>
</div>
{title} ({hits})

Conclusion

In this article we saw a possibility to make our dynamic navigation by adding an active effect to the menu. We have also implemented a basic method to separate the values of the navigation from the code that produces it, increasing the maintainability. In fact, if you need to add an item to the menu, all you have to do is to open the file navigation.txt and add the entry to the desired position. Add, remove, move operations are very simple and fast. The only aspect which provide a minimum of attention: after the last line of the file navigation.php there should not be line breaks, because it can be interpreted as a blank voice navigation.

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: , ,

The Author

Maurizio is married to the triad PHP - MySql - Apache and, not enough, he has a lover called jQuery. He has a blog where he tries to describe in detail all of "his lovers". His real specialty is the realization of large business application, altough he never refuses the commitment of a website.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

8 comments

  1. Newb
  2. weki
  3. Otodidakers

Trackback e pingback

  1. Tweets that mention How to build a dynamic and maintainable navigation | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by Antonino Scarfì and Web RSS News, soshableweb. soshableweb said: How to build …
  2. You are now listed on FAQPAL
    How to build a dynamic and maintainable navigation... In this article we will see how we can create a navigation that …

Leave a Reply

Current day month ye@r *