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
40
41
42
<?php declare(strict_types=1);

namespace App\Controller;

use Ibexa\Bundle\Core\Controller;
use Ibexa\Contracts\Core\Repository\LocationService;
use Ibexa\Contracts\Core\Repository\SearchService;
use Ibexa\Contracts\Core\Repository\Values\Content\LocationQuery;
use Ibexa\Contracts\Core\Repository\Values\Content\Query\Criterion;
use Symfony\Component\HttpFoundation\Response;

class BreadcrumbController extends Controller
{
    private LocationService $locationService;

    private SearchService $searchService;

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

    public function showBreadcrumbsAction($locationId): Response
    {
        $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(
            '@ibexadesign/parts/breadcrumbs.html.twig',
            [
                'breadcrumbs' => $breadcrumbs,
            ]
        );
    }
}

The controller uses the Ancestor Search Criterion to find all Ancestors of the current Location (line 27). 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="{{ ibexa_path( breadcrumb.valueObject ) }}">{{ breadcrumb.valueObject.contentInfo.name }}</a>
    {% else %}
        {{ breadcrumb.valueObject.contentInfo.name }}
    {% endif %}
{% endfor %}