public function EasyBreadcrumbStructuredDataJsonLd::value in Easy Breadcrumb 8
Same name and namespace in other branches
- 2.x src/EasyBreadcrumbStructuredDataJsonLd.php \Drupal\easy_breadcrumb\EasyBreadcrumbStructuredDataJsonLd::value()
Build JSON-LD value.
File
- src/
EasyBreadcrumbStructuredDataJsonLd.php, line 68
Class
- EasyBreadcrumbStructuredDataJsonLd
- Class EasyBreadcrumbStructuredDataJsonLd.
Namespace
Drupal\easy_breadcrumbCode
public function value() {
$value = FALSE;
$config = $this->configFactory
->get(EasyBreadcrumbConstants::MODULE_SETTINGS);
if ($config
->get(EasyBreadcrumbConstants::ADD_STRUCTURED_DATA_JSON_LD)) {
/** @var \Drupal\Core\Breadcrumb\Breadcrumb $breadcrumb */
$breadcrumb = $this->easyBreadcrumbBuilder
->build($this->routeMatch);
$links = $breadcrumb
->getLinks();
// Only fire if at least one link present.
if (count($links) > 0) {
// Open JSON.
$value = '{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [';
$position = 1;
/** @var \Drupal\Core\Link $link */
foreach ($links as $link) {
$name = $link
->getText();
$item = $link
->getUrl()
->setAbsolute(TRUE)
->toString();
// Escape " to produce valid json for titles with "" in them.
$name = str_replace('"', '\\"', $name);
$item = str_replace('"', '\\"', $item);
// Add a comma before each item except the first.
if ($position > 1) {
$value .= ',';
}
// Only add item if link's not empty.
if (!empty($item)) {
$value .= '{
"@type": "ListItem",
"position": "' . $position . '",
"name": "' . $name . '",
"item": "' . $item . '"
}';
}
else {
$value .= '{
"@type": "ListItem",
"position": "' . $position . '",
"name": "' . $name . '"
}';
}
// Increment position for next run.
$position++;
}
// Close JSON.
$value .= ']}';
}
}
return $value;
}