Skip to main content
Category:

Code snippet that can be used to load a list of translated taxonomy terms in Drupal 8.

<?php

namespace Drupal\mymodule\Controller;

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

/**
 * Class MyModuleController
 * @package Drupal\mymodule\Controller
 */
class MyModuleController extends ControllerBase
{

  /**
   * @return array
   */
  public function index()
  {
    $language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
    $vocabulary_name = 'tags';
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', $vocabulary_name);
    $tids = $query->execute();
    $terms = Term::loadMultiple($tids);
    $output = '<ul>';
    foreach ($terms as $term) {
      if($term->hasTranslation($language)){
        $tid = $term->id();
        $translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
        $name = $translated_term->getName();;
        $url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid]);
        $link = Link::fromTextAndUrl($name, $url);
        $link = $link->toRenderable();
        $output .= '<li>' . render($link) . '</li>';
      }
    }
    $output .= '</ul>';

    return array(
      '#type' => 'markup',
      '#markup' => $output
    );
  }

}

read this link to Load a list of taxonomy terms in Drupal 8 (Original language).

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook