Implementing A Breadcrumbs System On Your Site
This article briefly covers implementing a breadcrumbs / trail system. An example of this in action is on this web site (see above where it says “You are here”.
At the moment this article is really brief but eventually it shall be expanded on a bit further.
class Trail { var $path = array(); function Trail($includeHome = true, $homeLabel = 'Home', $homeLink = '/') { if ($includeHome) $this->addStep($homeLabel, $homeLink); } function addStep($title, $link = '') { $item = array('title' => $title); if (strlen($link) > 0) $item['link'] = $link; $this->path[] = $item; } }
Sample Usage
This assumes the above code is in a file called Trail.php somewhere within your PHP include_path. Additionally, you will need the Smarty Template Engine, which can be downloaded from http://smarty.php.net.
require_once('Trail.class.php'); require_once('Smarty.class.php'); $trail = new Trail(); $trail->addStep('News Archive', '/news'); $trail->addStep('Some Article'); $smarty = new Smarty(); $smarty->assign_by_ref('trail', $trail->path); $smarty->display('breadcrumbs.tpl');
Of course, you still need to render the trail. Here is a Smarty plugin function that can render a trail:
function smarty_function_breadcrumbs($params, &$smarty) { if (isset($params['trail']) && is_array($params['trail'])) $trail = &$params['trail']; else $trail = array(); if (isset($params['separator'])) $separator = $params['separator']; else $separator = ' > '; $length = (int) $params['length']; $links = array(); $trailSize = count($trail); for ($i = 0; $i < $trailSize; $i++) { if ($length > 0) { require_once $smarty->_get_plugin_filepath('modifier', 'truncate'); $title = smarty_modifier_truncate($trail[$i]['title'], $length); } else $title = $trail[$i]['title']; if (isset($trail[$i]['link']) && $i < $trailSize - 1) $links[] = '<a href="' . $trail[$i]['link'] . '" title="' . htmlSpecialChars($trail[$i]['title']) . '">' . $title . '</a>'; else $links[] = $title; } return join($separator . "\n", $links); }
Finally, you need to call this Smarty function from your template. Length is the maximum length a step can be before it’s truncated, separator is the string between each item. Based on the code usage above, the following code should be in your Smarty template directory in a file called breadcrumbs.tpl
<div id="breadcrumbs"> {breadcrumbs trail=$trail separator=" > " length=30} </div>
The final step is to style the breadcrumbs div:
#breadcrumbs { font-size : 85%; color : #000; margin-bottom : 5px; } #breadcrumbs a { color : #f00; } #breadcrumbs a:hover { color : #fff; background-color : #f00; }
Other Options
- Download a PDF version of this article
- Put your PHP knowledge to the test with our online and iPad/iPhone quizzes
- View or post comments for this article
- Browse similar articles by tag: PHP




