In mytheme.theme I have the following:

function mytheme_preprocess(&$variables) {
 $current_path = \Drupal::service('path.current')->getPath();
 $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
 $variables['currenttab'] = explode('/', $result)[1];

This function is extracting the first dirname from my url, for example, httttp://server/dirname/pagename it sets currenttab to 'dirname'.

It is working reasonably well, but I notice that if I click around on my site in a specific way, occasionally I get a page where the sidebar template has the correct {{ currenttab }} but the navbar has the {{ currenttab }} value from an older page.

I thought this theme preprocess would make {{ currenttab }} be the same in all my theme templates, but that does not appear to be the case. Once this problem appears, I can reload the page many times and it persists. I think this is related to the order in which I change urls.

What is going on here?

1 Answer 1


You would have to add a cache context:

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

Now you cache for each relative path a different version of the template.

However, it is not a good idea to add this context to all templates. Only add it to those templates you intend to use the variable, otherwise you fill up your cache with a lot of useless variations:

function mytheme_preprocess(&$variables, $hook) {
  if (in_array($hook, ['foo', 'bar'])) {
    $variables['#cache']['contexts'][] = 'url.path';
    // add variables depending on the relative url
  • I added this to my single preprocess function and it looks like it solves it, much thanks!! When you say "add it to those templates you intend to use.." do you mean I should have a preprocess hook for that template, and not have the cache in the most general preprocess function?
    – Innovine
    Commented Oct 4, 2019 at 12:39
  • You can still use the generic preprocess hook, but check $hook for the templates you want to target. See the code example I've added to the answer.
    – 4uk4
    Commented Oct 4, 2019 at 12:48
  • I'm digging into it now, thanks again!
    – Innovine
    Commented Oct 4, 2019 at 12:50

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.