1

In Drupal 8, I have a blog content type with a taxonomy term reference field called category.

How can I print out the Term ID of the taxonomy term of the category field in my node.html.twig file.

I can print the term name using {{ content.field_category }} but I also want to print out the term ID which should be a unique number. How should I go about doing this as I have search for days without any clue?

1

One "hacky" way to do this:

{# First step: capture the rendered output of the internal path link for a term #}  
{% set tid %}{{ content.field_category.0['#url'] }}{% endset %}

{# Second step: do some string processing on the captured output, removing the /taxonomy/term/ prefix and getting the TID #}  
{{ tid|trim|replace({ '/taxonomy/term/' : '' }) }}

Good luck!

1

I figured it out, I was able to print the term ID of the category field using:

{{ node.field_category.entity.tid.value }} as I realised I was looking in the wrong direction. Drupal 8 use entity reference only so I needed to call the TID from the referenced entity which of course is a taxonomy term in my category field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.