You are here

function template_preprocess_taxonomy_term in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/taxonomy/taxonomy.module \template_preprocess_taxonomy_term()
  2. 7 modules/taxonomy/taxonomy.module \template_preprocess_taxonomy_term()

Prepares variables for taxonomy term templates.

Default template: taxonomy-term.html.twig.

By default this function performs special preprocessing to move the name base field out of the elements array into a separate variable. This preprocessing is skipped if:

  • a module makes the field's display configurable via the field UI by means of BaseFieldDefinition::setDisplayConfigurable()
  • AND the additional entity type property 'enable_base_field_custom_preprocess_skipping' has been set using hook_entity_type_build().

Parameters

array $variables: An associative array containing:

  • elements: An associative array containing the taxonomy term and any fields attached to the term. Properties used:

  • attributes: HTML attributes for the containing element.

File

core/modules/taxonomy/taxonomy.module, line 112
Enables the organization of content into categories.

Code

function template_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#taxonomy_term'];

  /** @var \Drupal\taxonomy\TermInterface $term */
  $term = $variables['term'];
  $variables['url'] = !$term
    ->isNew() ? $term
    ->toUrl()
    ->toString() : NULL;

  // Make name field available separately.  Skip this custom preprocessing if
  // the field display is configurable and skipping has been enabled.
  // @todo https://www.drupal.org/project/drupal/issues/3015623
  //   Eventually delete this code and matching template lines. Using
  //   $variables['content'] is more flexible and consistent.
  $skip_custom_preprocessing = $term
    ->getEntityType()
    ->get('enable_base_field_custom_preprocess_skipping');
  if (!$skip_custom_preprocessing || !$term
    ->getFieldDefinition('name')
    ->isDisplayConfigurable('view')) {

    // We use name here because that is what appears in the UI.
    $variables['name'] = $variables['elements']['name'];
    unset($variables['elements']['name']);
  }
  $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);

  // Helpful $content variable for templates.
  $variables['content'] = [];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}