yii2框架-yii2的面包屑导航(十八)

这一节主要是总结关于yii2的面包屑导航的功能。其实也是比较简单,下面就说一下简单原理。

面包屑的类是yii\widgets\Breadcrumbs,代码如下:

 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\widgets;

use Yii;
use yii\base\Widget;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

/**
 * Breadcrumbs displays a list of links indicating the position of the current page in the whole site hierarchy.
 *
 * For example, breadcrumbs like "Home / Sample Post / Edit" means the user is viewing an edit page
 * for the "Sample Post". He can click on "Sample Post" to view that page, or he can click on "Home"
 * to return to the homepage.
 *
 * To use Breadcrumbs, you need to configure its [[links]] property, which specifies the links to be displayed. For example,
 *
 * ```php
 * // $this is the view object currently being used
 * echo Breadcrumbs::widget([
 *     'itemTemplate' => "<li><i>{link}</i></li>\n", // template for all links
 *     'links' => [
 *         [
 *             'label' => 'Post Category',
 *             'url' => ['post-category/view', 'id' => 10],
 *             'template' => "<li><b>{link}</b></li>\n", // template for this link only
 *         ],
 *         ['label' => 'Sample Post', 'url' => ['post/edit', 'id' => 1]],
 *         'Edit',
 *     ],
 * ]);
 * ```
 *
 * Because breadcrumbs usually appears in nearly every page of a website, you may consider placing it in a layout view.
 * You can use a view parameter (e.g. `$this->params['breadcrumbs']`) to configure the links in different
 * views. In the layout view, you assign this view parameter to the [[links]] property like the following:
 *
 * ```php
 * // $this is the view object currently being used
 * echo Breadcrumbs::widget([
 *     'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
 * ]);
 * ```
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Breadcrumbs extends Widget
{
    /**
     * @var string the name of the breadcrumb container tag.
     *这个是面包屑的包含标签,渲染模板后的面包屑最外层标签
     */
    public $tag = 'ul';
    /**
     * @var array the HTML attributes for the breadcrumb container tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     *这个值是对<ul>这个标签进行行内的样式或者属性设置,可以在使用是自动义设置各种属性。
     */
    public $options = ['class' => 'breadcrumb'];

    /**
    *@var array the default class of the tag(ul),array_merge($this->defaultoptions,$this->options);
    *这个是我自己重新定义的$defaultoptions变量,默认值['class' => 'breadcrumb']
    */
    public $defaultoptions = ['class' => 'breadcrumb'];
    /**
     * @var boolean whether to HTML-encode the link labels.
     */
    public $encodeLabels = true;
    /**
     * @var array the first hyperlink in the breadcrumbs (called home link).
     * Please refer to [[links]] on the format of the link.
     * If this property is not set, it will default to a link pointing to [[\yii\web\Application::homeUrl]]
     * with the label 'Home'. If this property is false, the home link will not be rendered.
     *这个是设置首页的link的属性
     */
    public $homeLink;
    /**
     * @var array list of links to appear in the breadcrumbs. If this property is empty,
     * the widget will not render anything. Each array element represents a single link in the breadcrumbs
     * with the following structure:
     *
     * ```php
     * [
     *     'label' => 'label of the link',  // required
     *     'url' => 'url of the link',      // optional, will be processed by Url::to()
     *     'template' => 'own template of the item', // optional, if not set $this->itemTemplate will be used
     * ]
     * ```
     *
     * If a link is active, you only need to specify its "label", and instead of writing `['label' => $label]`,
     * you may simply use `$label`.
     *
     * Since version 2.0.1, any additional array elements for each link will be treated as the HTML attributes
     * for the hyperlink tag. For example, the following link specification will generate a hyperlink
     * with CSS class `external`:
     *
     * ```php
     * [
     *     'label' => 'demo',
     *     'url' => 'http://example.com',
     *     'class' => 'external',
     * ]
     * ```
     *
     * Since version 2.0.3 each individual link can override global [[encodeLabels]] param like the following:
     *
     * ```php
     * [
     *     'label' => '<strong>Hello!</strong>',
     *     'encode' => false,
     * ]
     * ```
     *这个是设置其他下一级link的属性 
     */
    public $links = [];
    /**
     * @var string the template used to render each inactive item in the breadcrumbs. The token `{link}`
     * will be replaced with the actual HTML link for each inactive item.
     */
    public $itemTemplate = "<li>{link}</li>\n";
    /**
     * @var string the template used to render each active item in the breadcrumbs. The token `{link}`
     * will be replaced with the actual HTML link for each active item.
     */
    public $activeItemTemplate = "<li class=\"active\">{link}</li>\n";


    /**
     * Renders the widget.
     */
    public function run()
    {
    	//如果没有设置links,直接退出。
        if (empty($this->links)) {
            return;
        }
        $links = [];
        //如果没有设置homeLink属性,则启用默认的值
        if ($this->homeLink === null) {
            $links[] = $this->renderItem([
                'label' => Yii::t('yii', 'Home'),
                'url' => Yii::$app->homeUrl,
            ], $this->itemTemplate);
          //如果设置homeLink,则渲染该首页html模板
        } elseif ($this->homeLink !== false) {
            $links[] = $this->renderItem($this->homeLink, $this->itemTemplate);
        }
        //循环获取下一级的面包屑导航
        foreach ($this->links as $link) {
        	//如果不是数组(即是字符串),则设置$link数组只有一个属性label
            if (!is_array($link)) {
                $link = ['label' => $link];
            }
            //渲染下一级面包屑的模板
            $links[] = $this->renderItem($link, isset($link['url']) ? $this->itemTemplate : $this->activeItemTemplate);
        }
        //创建整个面包屑模板,这里修改成array_merge($this->defaultoptions,$this->options),继承合并options属性,可以实现<ul>标签设置不同样式
        echo Html::tag($this->tag, implode('', $links), array_merge($this->defaultoptions,$this->options));
    }

    /**
     * Renders a single breadcrumb item.
     * @param array $link the link to be rendered. It must contain the "label" element. The "url" element is optional.
     * @param string $template the template to be used to rendered the link. The token "{link}" will be replaced by the link.
     * @return string the rendering result
     * @throws InvalidConfigException if `$link` does not have "label" element.
     */
    protected function renderItem($link, $template)
    {
        $encodeLabel = ArrayHelper::remove($link, 'encode', $this->encodeLabels);
        //判定每一级的link数组是否存在key=‘label’
        if (array_key_exists('label', $link)) {
        	//存在就进行html的encode
            $label = $encodeLabel ? Html::encode($link['label']) : $link['label'];
        } else {
            throw new InvalidConfigException('The "label" element is required for each link.');
        }
        //
        if (isset($link['template'])) {
            $template = $link['template'];
        }
        if (isset($link['url'])) {

            $options = $link;
            //$options删除掉三个属性后,其余的属性例如class=>'myclass'等这些是<li>标签的样式属性设置
            unset($options['template'], $options['label'], $options['url']);
            //由于存在url,那么直接创建a的标签链接
            $link = Html::a($label, $link['url'], $options);
        } else {
        	//如果没有存在url,那么就只是显示一个label,没有跳转链接
            $link = $label;
        }
        	//$link模板内容替换$template的{link}变量
        return strtr($template, ['{link}' => $link]);
    }
}


那么在前端使用:

<?php
echo Breadcrumbs::widget([
    'itemTemplate' => "<li><i>{link}</i></li>\n", // template for all links
    'homeLink' => [
     		'label' => '首页',
	        'url' => ['user/index'],
	        'template' => "<li><b>{link}</b></li>\n",
	        'class' => 'myhome'
     	],
    'links' => [
	    [
	        'label' => 'Two',
	        'url' => ['post-category/view', 'id' => 10, 'name' => 'bing'],
	        'template' => "<li><b>{link}</b></li>\n",
	    ],
	    [
	    	'label' => 'Sample Post', 
	    	'url' => ['post/edit', 'id' => 1]
	    ],
	    'Edit',
    ],
    'options' => ['style' => 'background-color:#aaa']
 ]);	
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值