How do I make the same variable available to all my theme files? In mytheme.theme I have the following:

function mytheme_preprocess(&amp;$variables) {
 $current_path = \Drupal::service('path.current')-&gt;getPath();
 $result = \Drupal::service('path.alias_manager')-&gt;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?
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(&amp;$variables, $hook) {
  if (in_array($hook, ['foo', 'bar'])) {
    $variables['#cache']['contexts'][] = 'url.path';
    // add variables depending on the relative url
  }
}