Class Term missing sometimes when used in myTheme.theme Using my theme file, I created a theme/template suggestion for taxonomies. I load a term object so I can know its vid. This was working and still works most the time. However, occasionally I get fatal errors. Which is a big deal. Similar to:


  Fatal error: Class 'Term' not found in myTheme.theme on line 4.


I am not sure why the term class isn't found, and only sometimes? Any suggestions on how to prevent this error?

Most of the time rebuilding the cache would fix this but not always.

myTheme.theme

&lt;?php
function myTheme_theme_suggestions_page_alter(&amp;$suggestions, &amp;$vars) {
  if (\Drupal::routeMatch()-&gt;getRouteName() == 'entity.taxonomy_term.canonical' &amp;&amp; $tid = \Drupal::routeMatch()-&gt;getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term-&gt;getVocabularyId();
  }
}
The error is caused from the fact you didn't fully qualified the class name, which means you forgot the namespace of that class.

Or you use \Drupal\taxonomy\Entity\Term::load($tid); or you add a use \Drupal\taxonomy\Entity\Term; line at the top of the file. In this way, PHP knows where to find the class you reference.