Aug 04, 2017 in Drupal 8, Snippets

With this snippet, you will be able to render a list of tags in Drupal 8.

  use Drupal\taxonomy\Entity\Term;      
  use Drupal\Core\Link;
  use Drupal\Core\Url;

  $vocabulary_name = 'YOUR_VOCABULARY_NAME'; //name of your vocabulary
  $query = \Drupal::entityQuery('taxonomy_term');
  $query->condition('vid', $vocabulary_name);
  $query->sort('weight');
  $tids = $query->execute();
  $terms = Term::loadMultiple($tids);
  $output = '<ul>';
  foreach($terms as $term) {
      $name = $term->getName();;
      $url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]);
      $link = Link::fromTextAndUrl($name, $url);
      $link = $link->toRenderable();
      $output .='<li>'.render($link).'</li>';
  }
  $output .= '</ul>';
  print $output;