1

If I'm on a node, inside preprocess_page(&$variables), I can check

if (isset($variables['node']) && $variables['node']->bundle() == 'my-type')

to see if I'm on a node, and a node of a certain type.

Then I can get field information with

$variables['node']->field_icon->entity->getFileUri()

How can I do the same thing for a taxonomy term page to know that I'm on a taxonomy term page and get the field values?

1

To check term data in theme_preprocess_page for drupal 7. you can use below code.

if (arg(0) == 'taxonomy' && arg(1) == 'term') {
if (isset($variables['page']['content']['system_main']['term_heading']['term']['#term'])) {
  $term_data = $variables['page']['content']['system_main']['term_heading']['term']['#term'];
}

}

Hope this helps.

1

Unfortunately I don't think there is anything that the hook gives you directly that you can use in this instance. However you can always check the route name to determine if you are on a taxonomy term page.

// Will be "true" if you are currently on a taxonomy term page.
if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {

  // Since this is a taxonomy term page, you may wish to get the term ID.
  $term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
}
0

There is two ways to get the term in preprocess_page.

  1. Get the tid from parameter and then load the term.
  2. Get the Term directly from ParameterBag.
    Her is code snippet

use Drupal\taxonomy\Entity\Term;
/**
 * Implements hook_preprocess_HOOK().
 */
function myModule_preprocess_page(&$variables) {
  // Get the tid.
  $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
  // Load the term.
  $term = Term::load($tid);

   // Get possible params.
   /** @var \Symfony\Component\HttpFoundation\ParameterBag $possible_parameters */
   $possible_parameters = \Drupal::routeMatch()->getParameters();
    // Get term
    $term = $possible_parameters->get('taxonomy_term');
}

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.