Skip to content

Instantly share code, notes, and snippets.

@thamas
Last active June 9, 2023 11:57
Show Gist options
  • Save thamas/1ea09e1c190d95c8081e36d963f15ad1 to your computer and use it in GitHub Desktop.
Save thamas/1ea09e1c190d95c8081e36d963f15ad1 to your computer and use it in GitHub Desktop.
Display taxonomy term in Drupal Twig template translated
{#
/**
* @file
* Theme override to display a Talk node in Teaser view mode.
*
* The 'talk_category' variable was created in preprocess.
*/
#}
{# Other variables are excluded from this example to keep it simple. #}
{% include "@molecules/card/01-card.twig" with {
card_title: tt_category,
} %}
{#
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,
} %}
<?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();
}
}
@thamas
Copy link
Author

thamas commented May 12, 2022

Good to know @bmsimo! Also thanks for the update! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment