4

I'm trying to add the page title to the breadcrumbs for each page, unfortunately my breadcrumbs are not updating with current page title. All sibling pages in the menu show the same breadcrumbs.

For example, all these pages will show the same breadcrumbs:

Home > About Us > Our Team
Home > About Us > Our Mission
Home > About Us > Another Page

Whatever page you visit first, you will get the breadcrumbs for that page on all of the above pages. So if you visit the "Our Team" page first, you will get the "Our Team" breadcrumbs on the "Our Mission" and "Another Page" pages as well. The same happens for 2nd level pages.

So if you visit

Home > About Us

You will get the About Us breadcrumbs on

Home > Services

However, you will not get the Home > About Us> Our Team breadcrumbs on

Home > Services > Service A

I have this code in my .theme file:

function themename_preprocess_breadcrumb(&$variables){
   if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']){
       $variables['breadcrumb'][] = array(
                 'text' => $node->getTitle(),
                     'url' => $node->URL()
                   );
   }
}

And this for my breadcrumbs template:

{% if breadcrumb %}
  <nav class="breadcrumb" role="navigation" aria-labelledby="system-breadcrumb">
    <h2 id="system-breadcrumb" class="visually-hidden">{{ 'Breadcrumb'|t }}</h2>
    <ol>
    {% for item in breadcrumb %}
      <li>
        {% if item.url %}
          <a href="{{ item.url }}">{{ item.text }}</a>
        {% else %}
          {{ item.text }}
        {% endif %}
      </li>
    {% endfor %}
    </ol>
  </nav>
{% endif %}

I'm guessing it's some sort of caching issue, as it seems to happen per-session (different users will get stuck with different breadcrumbs depending on which pages they visit first).

Anyone know why this may be happening?

1

I ran into the same issue

https://www.drupal.org/node/2723061

function my_theme_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    /** @var \Drupal\node\NodeInterface $node */
    $variables['breadcrumb'][] = [
      'text' => $node->getTitle(),
      'url' => $node->toUrl(),
    ];
    $variables['#cache']['contexts'][] = 'url';
    $variables['#cache']['contexts'][] = 'session';
    $variables['#cache']['contexts'][] = 'user';      
  }
}

So:

$variables['#cache']['contexts'][] = 'session';
$variables['#cache']['contexts'][] = 'user';
$variables['#cache']['contexts'][] = 'url';   

did the trick for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.