Mantas Vaitkūnas
Mantas Vaitkūnas

Reputation: 744

How to modify zii.widgets.CBreadcrumbs auto generated html?

I need to modify Yii framework widget- zii.widgets.CBreadcrumbs. By default it prints:

<div class="breadcrumbs">
<a href="/dr/dr/public_html/">Home</a> » <span>News</span></div>

But i need:

<ul class="menu">
   <li><a href="/dr/dr/public_html/">Home</a></li>
   <li>News</li>
</ul>

So how could i change it?

Upvotes: 2

Views: 4863

Answers (1)

bool.dev
bool.dev

Reputation: 17478

  1. If you are using the latest version of Yii (1.1.11), then you have a few new options in CBreadcrumbs, namely: activeLinkTemplate and inactiveLinkTemplate and using these (and also tagName) you can easily achieve your requirement.

    You just need to add values for these options, in the file where you are including the breadcrumb widget, by default, it's in a layout file : protected/views/layouts/main.php , like this:

    <?php if(isset($this->breadcrumbs)):?>
        <?php $this->widget('zii.widgets.CBreadcrumbs', array(
            'links'=>$this->breadcrumbs,
    
            'tagName'=>'ul', // will change the container to ul
            'activeLinkTemplate'=>'<li><a href="{url}">{label}</a></li>', // will generate the clickable breadcrumb links 
            'inactiveLinkTemplate'=>'<li>{label}</li>', // will generate the current page url : <li>News</li>
            'homeLink'=>'<li><a href="'.Yii::app()->homeUrl.'">Home</a></li>' // will generate your homeurl item : <li><a href="/dr/dr/public_html/">Home</a></li>
        )); ?><!-- breadcrumbs -->
    <?php endif?>
    

    'activeLinkTemplate' generates links for active/clickable links, and 'inactiveLinkTemplate' generates the current url which is not clickable and has no url.

    {url} and {label} are the url and label values provided by each view's breadcrumb object. eg:-

    // in some view.php file, you'll see this
    $this->breadcrumbs=array( // array is label=>url
        'Label1'=>array('route1'),
        'Label2'=>array('route2'),
        'Label3',
    );
    
  2. If you are using versions before 1.1.11 then you'll have to extend the CBreadcrumbs class and modify the run() method to output breadcrumbs, enclosed in <li>. Once you see the existing run() method it'll become fairly clear to you how to do it.

Edit:

Missed out how to add the css class. You can do this by adding a class key-value in the htmlOptions array for this widget :

<?php $this->widget('zii.widgets.CBreadcrumbs', array(
    'links'=>$this->breadcrumbs,

    'tagName'=>'ul', // will change the container to ul
    'htmlOptions'=>array('class'=>'menu'),
    // ... rest of the code ...
 )); ?><!-- breadcrumbs -->

Upvotes: 14

Related Questions