Yii 1.1: How to create a breadcrumb widget

11 followers

Here's a simple way to create a breadcrumb widget to be used in your templates. The idea is just to isolate how the breadcrumb is generated based on an array of crumbs.

Info: Please note, that new versions of Yii Framework already contain a bulit-in breadcrumbs widget. See this class reference chapter for more information. Information in this article may be, however, usable to build custom one, not descending from bulit-in one.

components/BreadCrumb.php:

<?php
class BreadCrumb extends CWidget {
 
    public $crumbs = array();
    public $delimiter = ' / ';
 
    public function run() {
        $this->render('breadCrumb');
    }
 
}
?>

components/views/breadCrumb.php:

<div id="breadCrumb">   
    <?php 
    foreach($this->crumbs as $crumb) {
        if(isset($crumb['url'])) {
            echo CHtml::link($crumb['name'], $crumb['url']);
        } else {
            echo $crumb['name'];
        }
        if(next($this->crumbs)) {
            echo $this->delimiter;
        }
    }
    ?>
</div>

Usage in views

<?php $this->widget('application.components.BreadCrumb', array(
  'crumbs' => array(
    array('name' => 'Home', 'url' => array('site/index')),
    array('name' => 'Login'),
  ),
  'delimiter' => ' &rarr; ', // if you want to change it
)); ?>

Total 4 comments

#13326 report it
Rohit Singhal at 2013/05/22 11:23am
nice one

nice explanation.

#728 report it
napeHeK at 2010/03/10 12:41pm
note

<?php class BreadCrumb extends CWidget { public $crumbs = array(); public $delimiter = ' ยป ';

public function run()
{
    foreach($this->crumbs as $key => $crumb)
    {
        if(isset($crumb['url'])) 
            $this->crumbs[$key] = CHtml::link($crumb['name'], $crumb['url']);
        else
            $this->crumbs[$key] = $crumb['name'];
    }

    $crumbs = implode($this->delimiter, $this->crumbs);
    $this->render('breadCrumb', array('crumbs' => $crumbs));
}

}

#1403 report it
nickelstar at 2009/08/11 09:12pm
Auto Breadcrumb Widget

In an attempt to expand on this example, I created a breadcrumb widget that automatically manages some features. Please take a look here for details:

http://www.yiiframework.com/forum/index.php?/topic/3741-auto-breadcrumbs/

#1832 report it
jonah at 2009/03/19 06:25pm
note

I'm hesitant to change this myself as I did not put work into writing this article but I prefer this shorthand way of defining crumbs:

<?php $this->widget('application.components.BreadCrumb', array(
   'crumbs' => array(
       array('Home', array('site/index')),
       array('Login'),
   )
)); ?>

eg no array keys defined.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: knut
  • Updated by: Yang He
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +12
  • Viewed: 49,972 times
  • Created on: Mar 19, 2009
  • Last updated: Jun 29, 2012