Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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 (Drupal & Laravel)

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

Web Posts

Search

Page Facebook