How to create Yii2 Breadcrumbs

2019-04-09 03:15发布

问题:

I am looking for yii2 beadcrumb code

I have layout page in twig want to add breadcrumb there and want to update it according to pages for example

Dashboard/Employees/Add Employee

Dashboard/Employee/Edit Employee

Dashboard and employee will be clickable

I got very less information on yii2 breadcrumbs on internet.

回答1:

In your main layout use:

<?= 
   Breadcrumbs::widget([
      'homeLink' => [ 
                      'label' => Yii::t('yii', 'Dashboard'),
                      'url' => Yii::$app->homeUrl,
                 ],
      'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
   ]) 
?>

And in your view:

$this->title = 'Add Employee';
$this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

This will generate the following breadcrumbs:

Dashboard / Employees / Add Employee


回答2:

In your layout-

//use yii\widgets\Breadcrumbs;

<?= 
   Breadcrumbs::widget([
        'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
   ]) 
?>

In your view-

$this->title = 'Example';
$this->params['breadcrumbs'][] = $this->title;

Hope it will work.



回答3:

My Code looks like this:

<section class="content-header">
    <ol class="breadcrumb">
        <?php
        echo Breadcrumbs::widget([
          'itemTemplate' => "<li><i>{link}</i></li>\n", 
          'homeLink' => [ 
            'label' => Yii::t('yii', 'Dashboard'),
            'url' => Yii::$app->homeUrl,
          ],
           'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
       ]);
        ?>
     </ol>
    </section>

and on any of the view page it I add a snippet

$this->params['breadcrumbs'][] = "Item Details";

The above is a simple example. The issue with this is that it does not truly give out the tree structure for navigation. I will have to write a helper function to track the history or tree path for each view page.



标签: yii2