5

I'm currently using the preprocess_breadcrumb hook in my .theme file to customize the output of my breadcrumbs like so:

function mytheme_preprocess_breadcrumb(&$variables){
    $node = \Drupal::routeMatch()->getParameter('node');
    $current_path = \Drupal::service('path.current')->getPath();
    $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $crumbs = explode("/", $result);
    if($node){
        $variables['current_title'] = $node->getTitle();
        $variables['crumbs'] = $crumbs;
    }
}

I then use breadcrumb.html.twig to use these new variables like so

    <nav role="navigation" aria-labelledby="system-breadcrumb">
    <h2 id="system-breadcrumb" class="visually-hidden">{{ 'You are here'|t }}</h2>
    <ul class="breadcrumbs">
        {% for crumb in crumbs %} 
            {% if loop.first %}
        <li><a href="./">Home</a></li>
        {% elseif loop.last %}
        <li class="current"><a href="#">{{ current_title }}</a></li> 
        {% elseif crumb == 'node' %}
        {% else %}
        <li> <a href="../{{ crumb }}">{{ crumb }}</a></li>
        {% endif %}
        {% endfor %}
    </ul>
</nav>
{% endif %}

However I'd like it more if all this was encapsulated in a module. In mymodule.module file I have

function mymodule_preprocess_breadcrumb(&$variables){
$node = \Drupal::routeMatch()->getParameter('node');
$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
$crumbs = explode("/", $result);
if($node){
    $variables['current_title'] = $node->getTitle();
    $variables['crumbs'] = $crumbs;
}

}

But this function never fires. Is there a way to use the preprocess_breadcrumb hook from a module?

1
  • As side note, if you want to alter the breadcrumbs, that is not the code you should implement. You need at least to create a service using a class like BookBreadcrumbBuilder.
    – avpaderno
    Commented Aug 2, 2016 at 21:29

1 Answer 1

4

Preprocess hooks work in themes and modules. It doesn't matter where you put it, the only difference is, that modules have higher priority.

What you have to do is to work on caching. Because of the variables you put in, you need a cache context on url.path,

$variables['#cache']['contexts'][] = 'url.path';

That doesn't make a difference for the first run after clearing the cache, but makes sure that the hook is run for every new path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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