Skip to content

Add breadcrumbs

To add breadcrumbs to your website, first prepare a general layout template in a templates/themes/<theme_name>/pagelayout.html.twig file.

This template can contain things such as header, menu, footer, as well as assets for the whole site, and all other templates extend it.

Then, to render breadcrumbs, create a BreadcrumbController.php file in src/Controller:

 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
<?php

namespace App\Controller;

use eZ\Bundle\EzPublishCoreBundle\Controller;
use eZ\Publish\API\Repository\LocationService;
use eZ\Publish\API\Repository\SearchService;
use eZ\Publish\API\Repository\Values\Content\LocationQuery;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion;

class BreadcrumbController extends Controller
{
    private $locationService;

    private $searchService;

    public function __construct(LocationService $locationService, SearchService $searchService)
    {
        $this->locationService = $locationService;
        $this->searchService = $searchService;
    }

    public function showBreadcrumbsAction($locationId)
    {
        $query = new LocationQuery();
        $query->query = new Criterion\Ancestor([$this->locationService->loadLocation($locationId)->pathString]);

        $results = $this->searchService->findLocations($query);
        $breadcrumbs = [];
        foreach ($results->searchHits as $searchHit) {
            $breadcrumbs[] = $searchHit;
        }

        return $this->render('@ezdesign/parts/breadcrumbs.html.twig', [
                'breadcrumbs' => $breadcrumbs,
            ]
        );
    }
}

The controller uses the Ancestor Search Criterion to find all Ancestors of the current Location (line 26). It then places the ancestors in the breadcrumbs variable that you can use in the template.

Next, call this controller from the page layout template and pass the current Location ID as a parameter:

1
2
3
4
5
6
7
8
{{ render(
    controller(
        "App\\Controller\\BreadcrumbController::showBreadcrumbsAction",
        {
            'locationId': locationId,
        }
    )
) }}

Finally, create a breadcrumb template in templates/themes/<theme_name>/parts/breadcrumbs.html.twig, as indicated in the controller (line 34). In this template, iterate over all breadcrumbs and render links to them:

1
2
3
4
5
6
7
8
{% for breadcrumb in breadcrumbs %}
    {% if not loop.first %} -> {% endif %}
    {% if not loop.last %}
        <a href="{{ ez_path( breadcrumb.valueObject ) }}">{{ breadcrumb.valueObject.contentInfo.name }}</a>
    {% else %}
        {{ breadcrumb.valueObject.contentInfo.name }}
    {% endif %}
{% endfor %}