0 follower

Final Class Yiisoft\Yii\Widgets\Breadcrumbs

InheritanceYiisoft\Yii\Widgets\Breadcrumbs » Yiisoft\Widget\Widget

Breadcrumbs displays a list of items indicating the position of the current page in the site hierarchy.

For example, breadcrumbs like "Home / Sample Post / Edit" mean 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 {@see \Yiisoft\Yii\Widgets\Breadcrumbs::items()} method, which specifies the items to be displayed. For example:

echo Breadcrumbs::widget()
    ->itemTemplate("<li><i>{link}</i></li>\n") // template for all links
    ->items([
        [
            '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 appear on nearly every page of a website, you may consider placing this widget in a layout view. You can use a view parameter (e.g. $this->setParameter('breadcrumbs', [...])) to configure the items in different views.

In the layout view, assign this view parameter to the {@see \Yiisoft\Yii\Widgets\Breadcrumbs::items()} method like the following:

echo Breadcrumbs::widget()->items($this->getParameter('breadcrumbs', []));

In the examples above, $this is an instance of {@see \Yiisoft\View\ViewInterface} and refers to the current view.

Public Methods

Hide inherited methods

Method Description Defined By
activeItemTemplate() Returns a new instance with the specified active item template. Yiisoft\Yii\Widgets\Breadcrumbs
attributes() Returns a new instance with the HTML attributes for the breadcrumbs container tag. Yiisoft\Yii\Widgets\Breadcrumbs
container() Returns a new instance with whether the container is enabled. Default is false. Yiisoft\Yii\Widgets\Breadcrumbs
containerAttributes() Returns a new instance with the specified container HTML attributes. Yiisoft\Yii\Widgets\Breadcrumbs
containerClass() Returns a new instance with the specified container class. Yiisoft\Yii\Widgets\Breadcrumbs
containerTag() Returns a new instance with the specified container tag. Yiisoft\Yii\Widgets\Breadcrumbs
homeItem() Returns a new instance with the specified first item in the breadcrumbs (called home link). Yiisoft\Yii\Widgets\Breadcrumbs
id() Returns a new instance with the specified Widget ID. Yiisoft\Yii\Widgets\Breadcrumbs
itemTemplate() Returns a new instance with the specified item template. Yiisoft\Yii\Widgets\Breadcrumbs
items() Returns a new instance with the specified list of items. Yiisoft\Yii\Widgets\Breadcrumbs
jsonLd() Returns a new instance with JSON-LD structured data rendering enabled or disabled. Yiisoft\Yii\Widgets\Breadcrumbs
render() Renders the widget. Yiisoft\Yii\Widgets\Breadcrumbs
renderJsonLd() Renders JSON-LD structured data for the breadcrumbs. Yiisoft\Yii\Widgets\Breadcrumbs
tag() Returns a new instance with the specified tag. Yiisoft\Yii\Widgets\Breadcrumbs

Method Details

Hide inherited methods

activeItemTemplate() public method

Returns a new instance with the specified active item template.

public self activeItemTemplate ( string $value )
$value 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 function activeItemTemplate(string $value): self
{
    $new = clone $this;
    $new->activeItemTemplate = $value;
    return $new;
}

            
attributes() public method

Returns a new instance with the HTML attributes for the breadcrumbs container tag.

public self attributes ( array $valuesMap )
$valuesMap array

Attribute values indexed by attribute names.

                public function attributes(array $valuesMap): self
{
    $new = clone $this;
    $new->attributes = $valuesMap;
    return $new;
}

            
container() public method

Returns a new instance with whether the container is enabled. Default is false.

public self container ( boolean $value )
$value boolean

Whether the container is enabled.

                public function container(bool $value): self
{
    $new = clone $this;
    $new->container = $value;
    return $new;
}

            
containerAttributes() public method

Returns a new instance with the specified container HTML attributes.

public self containerAttributes ( array $valuesMap )
$valuesMap array

Attribute values indexed by attribute names.

                public function containerAttributes(array $valuesMap): self
{
    $new = clone $this;
    $new->containerAttributes = $valuesMap;
    return $new;
}

            
containerClass() public method

Returns a new instance with the specified container class.

public self containerClass ( string $value )
$value string

The container class.

                public function containerClass(string $value): self
{
    $new = clone $this;
    $new->containerClass = $value;
    return $new;
}

            
containerTag() public method

Returns a new instance with the specified container tag.

public self containerTag ( string $value )
$value string

The container tag.

                public function containerTag(string $value): self
{
    /**
     * @psalm-suppress TypeDoesNotContainType This check is necessary to ensure that an empty string is
     * not accepted, as the type declaration alone cannot enforce non-empty strings.
     */
    if ($value === '') {
        throw new InvalidArgumentException('Tag name must be a string and cannot be empty.');
    }
    $new = clone $this;
    $new->containerTag = $value;
    return $new;
}

            
homeItem() public method

Returns a new instance with the specified first item in the breadcrumbs (called home link).

If null is specified, the home item will not be rendered.

public self homeItem ( ?array $value )
$value ?array

Home item configuration. The format is the same as an item in {@see \Yiisoft\Yii\Widgets\items()}.

throws InvalidArgumentException

If an empty array is specified.

                public function homeItem(?array $value): self
{
    /** @psalm-suppress TypeDoesNotContainType */
    if ($value === []) {
        throw new InvalidArgumentException(
            'The home item cannot be an empty array. To disable rendering of the home item, specify null.',
        );
    }
    $new = clone $this;
    $new->homeItem = $value;
    return $new;
}

            
id() public method

Returns a new instance with the specified Widget ID.

public self id ( ?string $value )
$value ?string

The id of the widget.

                public function id(?string $value): self
{
    /** @psalm-suppress TypeDoesNotContainType */
    if ($value === '') {
        throw new InvalidArgumentException('The id cannot be an empty string.');
    }
    $new = clone $this;
    $new->attributes['id'] = $value;
    return $new;
}

            
itemTemplate() public method

Returns a new instance with the specified item template.

public self itemTemplate ( string $value )
$value 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 function itemTemplate(string $value): self
{
    $new = clone $this;
    $new->itemTemplate = $value;
    return $new;
}

            
items() public method

Returns a new instance with the specified list of items.

public self items ( array $value )
$value array

List of items to appear in the breadcrumbs. If this property is empty, the widget will not render anything. Each array element represents a single item in the breadcrumbs with the following structure:

[
    'label' => 'label of the item',  // required
    'url' => 'url of the item',      // optional
    'template' => 'own template of the item', // optional, if not set $this->itemTemplate will be used
    'encode' => true, // optional, whether to HTML-encode the label, defaults to true
]

If an item is active, you only need to specify its "label", and instead of writing ['label' => $label], you may simply use $label.

Additional array elements will be treated as HTML attributes for the hyperlink tag. For example, the following item specification will generate a hyperlink with CSS class external:

[
    'label' => 'demo',
    'url' => 'http://example.com',
    'class' => 'external',
]

To disable encode for a specific item, you can set the encode option to false:

[
    'label' => '<strong>Hello!</strong>',
    'encode' => false,
]

                public function items(array $value): self
{
    $new = clone $this;
    $new->items = $value;
    return $new;
}

            
jsonLd() public method

Returns a new instance with JSON-LD structured data rendering enabled or disabled.

When enabled, a <script type="application/ld+json"> block with BreadcrumbList structured data is appended to the widget output.

public self jsonLd ( boolean $value )
$value boolean

Whether to render JSON-LD structured data.

                public function jsonLd(bool $value): self
{
    $new = clone $this;
    $new->jsonLd = $value;
    return $new;
}

            
render() public method

Renders the widget.

public string render ( )
return string

The result of widget execution to be outputted.

throws InvalidArgumentException

If an item has an invalid format.

                public function render(): string
{
    if ($this->items === []) {
        return '';
    }
    $items = [];
    if ($this->homeItem !== null) {
        $items[] = $this->renderItem($this->homeItem, $this->itemTemplate);
    }
    foreach ($this->items as $item) {
        if (!is_array($item)) {
            $item = ['label' => $item];
        }
        if ($item !== []) {
            $items[] = $this->renderItem(
                $item,
                isset($item['url']) ? $this->itemTemplate : $this->activeItemTemplate,
            );
        }
    }
    $body = implode('', $items);
    $result = empty($this->tag)
        ? $body
        : Html::normalTag($this->tag, PHP_EOL . $body, $this->attributes)->encode(false)->render();
    if ($this->container) {
        $containerAttributes = $this->containerAttributes;
        if ($this->containerClass !== '') {
            Html::addCssClass($containerAttributes, $this->containerClass);
        }
        $result = Html::normalTag($this->containerTag, PHP_EOL . $result . PHP_EOL, $containerAttributes)
            ->encode(false)
            ->render();
    }
    if ($this->jsonLd) {
        $result .= PHP_EOL . $this->renderJsonLd();
    }
    return $result;
}

            
renderJsonLd() public method

Renders JSON-LD structured data for the breadcrumbs.

public string renderJsonLd ( )
return string

The <script type="application/ld+json"> block with BreadcrumbList structured data.

                public function renderJsonLd(): string
{
    $listElements = [];
    $position = 1;
    if ($this->homeItem !== null) {
        $element = $this->buildJsonLdItem($this->homeItem, $position);
        if ($element !== null) {
            $listElements[] = $element;
            $position++;
        }
    }
    foreach ($this->items as $item) {
        if (!is_array($item)) {
            $item = ['label' => $item];
        }
        if ($item === []) {
            continue;
        }
        $element = $this->buildJsonLdItem($item, $position);
        if ($element !== null) {
            $listElements[] = $element;
            $position++;
        }
    }
    $data = [
        '@context' => 'https://schema.org',
        '@type' => 'BreadcrumbList',
        'itemListElement' => $listElements,
    ];
    $json = json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
    return '<script type="application/ld+json">' . $json . '</script>';
}

            
tag() public method

Returns a new instance with the specified tag.

public self tag ( string $value )
$value string

The container tag name. If an empty string is provided, the widget will not render a wrapping container tag.

                public function tag(string $value): self
{
    $new = clone $this;
    $new->tag = $value;
    return $new;
}