Last active
June 9, 2023 11:57
-
-
Save thamas/1ea09e1c190d95c8081e36d963f15ad1 to your computer and use it in GitHub Desktop.
Display taxonomy term in Drupal Twig template translated
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# | |
It is a simple solution if there are not to much languages to support. | |
The example uses a component based aproach. Look for Emulsify theme for more info. | |
#} | |
{# Get the translated taxonomy term. #} | |
{% set pill_text_nl = node.field_talk_category.entity.translation('nl').name.value %} | |
{% set pill_text_fr = node.field_talk_category.entity.translation('fr').name.value %} | |
{# The next definition uses the Global variables module. #} | |
{% set current_lang = global_variables.current_langcode %} | |
{# Set the correct translation depending on the actually used language. #} | |
{% if current_lang == 'nl' %} | |
{% if pill_text_nl %} | |
{% set pill_text = pill_text_nl %} | |
{% endif %} | |
{% elseif current_lang == 'fr' %} | |
{% if pill_text_fr %} | |
{% set pill_text = pill_text_fr %} | |
{% endif %} | |
{% endif %} | |
{# Other variables are excluded from this example to keep it simple. #} | |
{% include "@pages/_page.twig" with { | |
hero_pill_text: pill_text, | |
} %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implemets hook_preprocess_node(). | |
* | |
* Create variable from translated taxonomy term name. | |
* Code by @tikaszvince. | |
*/ | |
function THEMENAME_preprocess_node(&$variables) { | |
/** @var Drupal\node\Entity\Node $node */ | |
$node = &$variables['elements']['#node']; | |
if ( | |
$node->hasField('field_talk_category') | |
&& !$node->get('field_talk_category')->isEmpty() | |
) { | |
/** @var \Drupal\taxonomy\TermInterface $category */ | |
$category = $node->field_talk_category->entity; | |
$current_langcode = $node->language()->getId(); | |
if ($category->hasTranslation($current_langcode)) { | |
$category = $category->getTranslation($current_langcode); | |
} | |
$variables['#cache'] += ['tags' => []]; | |
$variables['#cache']['tags'] = array_merge($variables['#cache']['tags'], $category->getCacheTags()); | |
$variables['talk_category'] = $category->label(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey! This helped me a lot! Thanks, here's an update i thought i'd add: