📜  drupal 8 按词汇名称获取分类术语 - PHP (1)

📅  最后修改于: 2023-12-03 14:40:53.085000             🧑  作者: Mango

/**
 * Implements hook_preprocess_HOOK() for theme preprocess functions.
 *
 * Prepares variables for theme templates.
 *
 * @param array &$variables
 *   An array of variables to pass to the theme template.
 */
function YOUR_THEME_preprocess(&$variables) {
  // Load the taxonomy term storage service.
  $term_storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');

  // Get the vocabulary ID of the taxonomy vocabulary you want to fetch terms from.
  $vocabulary_id = 'YOUR_VOCABULARY_ID';

  // Load the vocabulary.
  $vocabulary = \Drupal\taxonomy\Entity\Vocabulary::load($vocabulary_id);

  // Get all terms from the specified vocabulary.
  $terms = $term_storage->loadTree($vocabulary->id());

  // Generate a list of terms with their respective descriptions.
  $term_list = [];
  foreach ($terms as $term) {
    // Load the term entity.
    $term_entity = \Drupal\taxonomy\Entity\Term::load($term->tid);

    // Retrieve the term name and description.
    $term_name = $term_entity->getName();
    $term_description = $term_entity->get('description')->getValue()[0]['value'];

    // Add the term name and description to the term list.
    $term_list[] = "- **$term_name**: $term_description";
  }

  // Convert the term list to a markdown formatted string.
  $term_list_markdown = implode("\n", $term_list);

  // Set the term list as a variable to be used in your theme templates.
  $variables['term_list'] = $term_list_markdown;
}

You can then use the $term_list variable in your theme templates to display the list of taxonomy terms with their descriptions. For example, in your node.html.twig or page.html.twig file, you can output the term list like this:

{{ term_list|raw }}

Make sure to replace 'YOUR_THEME' with the machine name of your theme and 'YOUR_VOCABULARY_ID' with the vocabulary ID of the taxonomy vocabulary you want to retrieve terms from.