yii2-breadcrumbs

Без микроразметки (yii\widgets\Breadcrumbs)

<ul class="breadcrumb">
    <li>
        <a class="home" href="/">Home</a>
    </li>
    <li>
        <a href="/catalog">Catalog</a>
    </li>
    <li class="active">
        Computers
    </li>
</ul>

С микроразметкой Microdata и Schema.org (common\widgets\BreadcrumbsMicrodata)

<ul class="breadcrumb" itemscope itemtype="http://schema.org/BreadcrumbList">
    <li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
        <a class="home" href="/" itemprop="item">
            <span itemprop="name">Home</span>
        </a>
        <meta itemprop="position" content="1">
    </li>
    <li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
        <a href="/catalog" itemprop="item">
            <span itemprop="name">Catalog</span>
        </a>
        <meta itemprop="position" content="2">
    </li>
    <li class="active" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
        <span itemprop="item">
            <span itemprop="name">Computers</span>
        </span>
        <meta itemprop="position" content="3">
    </li>
</ul>

Инструмент проверки структурированных данных — Google

Валидатор микроразметки — Яндекс

Код Yii2 виджета BreadcrumbsMicrodata


<?php

/**
 * Yii2 Breadcrumbs (хлебные крошки) с микроразметкой Schema.org
 */

namespace common\widgets;

use yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\Breadcrumbs;

/**
 * Breadcrumbs with Microdata markup from Schema.org
 * @supplemented Max <anywebdev@gmail.com>
 */
class BreadcrumbsMicrodata extends Breadcrumbs
{

    public $itempropPosition = 1;

    public function run()
    {
        if (empty($this->links)) {
            return;
        }

        $links = [];

        $replacement = ['>{link}' => ' itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">{link}{position}'];
        //todo: , '<img ' => '<img itemprop="image" '
        $this->itemTemplate = strtr($this->itemTemplate, $replacement);
        $this->activeItemTemplate = strtr($this->activeItemTemplate, $replacement);

        if ($this->homeLink === null) {
            $links[] = $this->renderItemMarkup(
                [
                    'label' => Yii::t('yii', 'Home'),
                    'url' => Yii::$app->homeUrl,
                ],
                $this->itemTemplate,
                $this->itempropPosition
            );
        } elseif ($this->homeLink !== false) {
            $this->homeLink['template'] = isset($this->homeLink['template']) ? strtr($this->homeLink['template'], $replacement) : $this->itemTemplate;
            $links[] = $this->renderItemMarkup(
                $this->homeLink,
                $this->homeLink['template'],
                $this->itempropPosition
            );
        }

        foreach ($this->links as $link) {
            if (!is_array($link)) {
                $link = ['label' => $link];
            }

            $links[] = $this->renderItemMarkup(
                $link,
                isset($link['url']) ? $this->itemTemplate : $this->activeItemTemplate,
                ++$this->itempropPosition
            );

        }

        echo Html::tag(
            $this->tag,
            implode('', $links),
            array_merge(
                $this->options,
                ["itemscope itemtype" => "http://schema.org/BreadcrumbList"]
            )
        );

    }

    protected function renderItemMarkup($link, $template, $position)
    {
        $encodeLabel = ArrayHelper::remove($link, 'encode', $this->encodeLabels);

        if (array_key_exists('label', $link)) {
            $label = Html::tag('span', $encodeLabel ? Html::encode($link['label']) : $link['label'], ['itemprop' => "name"]);
        } 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;
            unset($options['template'], $options['label'], $options['url']);
            $link = Html::a($label, $link['url'], array_merge($options, ["itemprop" => "item"]));
        } else {
            $link = Html::tag('span', $label, ["itemprop" => "item"]);
        }

        return strtr($template,
            [
                '{link}' => $link,
                '{position}' => Html::tag('meta', '', ['itemprop' => "position", "content" => $position])
            ]
        );
    }

}


Пример подключения виджета


<?= BreadcrumbsWidget::widget([
    'options' => [
        'class' => 'breadcrumb',
    ],
    'homeLink' => [
        'label' => Yii::t('yii', 'Home'),
        'url' => ['/site/index'],
        'class' => 'home',
        'template' => '<li>{link}</li>',
    ],
    'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
    'itemTemplate' => '<li>{link}</li>',
    'activeItemTemplate' => '<li class="active">{link}</li>',
    'tag' => 'ul',
    'encodeLabels' => false
]);
?>

Пример добавления breadcrumbs во view


$this->params['breadcrumbs'][] = ['label' => 'Catalog', 'url' => ['catalog/']];
$this->params['breadcrumbs'][] = ['label' => 'Computers'];

Пример добавления breadcrumbs в controller’е


$this->view->params['breadcrumbs'][] = ['label' => 'Catalog', 'url' => ['catalog/']];
$this->view->params['breadcrumbs'][] = ['label' => 'Computers'];

3 ответы
    • admin
      admin говорит:

      Например, в файле \common\widgets\BreadcrumbsMicrodata.php,
      а в \frontend\views\layouts\main.php заменить вызов Breadcrumbs::widget на \common\widgets\BreadcrumbsMicrodata::widget

      Ответить

Ответить

Хотите присоединиться к обсуждению?
Не стесняйтесь вносить свой вклад!

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *