Breadcrumbs.php
2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace thread\modules\seo\widgets\breadcrumbs;
use Yii;
use yii\helpers\{
Url, Html
};
use thread\app\web\View;
/**
* Class Breadcrumbs
*
* @package thread\modules\seo\widgets\breadcrumbs
* @author FilamentV <vortex.filament@gmail.com>
* @copyright (c), Thread
*/
class Breadcrumbs extends \yii\widgets\Breadcrumbs
{
public $itemsLdJson = [];
/**
* @param mixed $result
* @return mixed
*/
public function afterRun($result)
{
$this->generateLdJson();
return parent::afterRun($result);
}
/**
*
*/
public function generateLdJson()
{
$view = Yii::$app->getView();
$this->generateItemLdJson();
$itemsStr = [];
if (!empty($this->itemsLdJson)) {
foreach ($this->itemsLdJson as $key => $item) {
$itemsStr[] = '{
"@type": "ListItem",
"position": ' . ($key + 1) . ',
"item": {
"@id": "' . $item['url'] . '",
"name": "' . $item['label'] . '"
}
}';
}
}
$js = '
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [' . implode(',', $itemsStr) . '
]
}';
$view->registerJsLdJson($js, View::POS_END);
}
/**
*
*/
public function generateItemLdJson()
{
if ($this->homeLink === null) {
$this->itemsLdJson[] = [
'label' => Yii::t('yii', 'Home'),
'url' => Url::toRoute(Yii::$app->homeUrl, true),
];
} elseif ($this->homeLink !== false) {
if (isset($this->homeLink['label']) && isset($this->homeLink['url'])) {
$this->itemsLdJson[] = [
'label' => Html::encode($this->homeLink['label']),
'url' => Url::toRoute($this->homeLink['url'], true),
];
}
}
foreach ($this->links as $link) {
if (isset($link['label']) && isset($link['url'])) {
$this->itemsLdJson[] = [
'label' => Html::encode($link['label']),
'url' => Url::toRoute($link['url'], true),
];
}
}
}
}