0
votes

Having trouble printing taxonomy terms in a Drupal twig template. Hoping someone can help.

I have a taxonomy vocabulary called "FAQ Category". Inside of it, there are several terms. I am trying to print all terms in a twig template called views-view--faqs.html.twig.

So far, I am able to print the term of the current page by using:

{{ data.title|raw }}

I can print the next and previous terms on the same page by using data.previous.label and data.next.label, and those are working fine.

What I need is to print all the terms, and I'm stuck. Ive tried several variations of for loops, such as:

{% for item in data %}
    {{ data.title|raw }}
{% endfor %}

But that is not working. Any idea what I can do to print all of the terms?

4

4 Answers

1
votes

Your template file, looking by the name is pointing to a specific view. I believe there is more than 1 ways to achieve it, but i suggest you to use a hook preprocess view.

check the docs here:https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/function/template_preprocess_views_view/8.2.x

Important: you will need to paste that code inside mytheme.theme file (usually in themes/custom/mythemename, where mythemename is the name of your custom theme)

In the above link example, just add some new data, like this

$variables["mynewvar"] = 'my data';

then, you can print it into template

{{ mynewvar }}

Inside that hook, i would write an Entity Query in order to get all desired taxonomies.

Check this example https://drupal.stackexchange.com/questions/144147/get-taxonomy-terms

Then, i would append this values into the twig context, just like 'myvar' example.

0
votes

I tried this, no luck. I was hoping that since I can already call in terms using data.next.label and data.previous.label, that there would be an easy way to just call all of them.

I tried this to get all the variables of data:

{% for key, value in data  %}
    {{ key }}
{% endfor %}

and got values returned of: title, items, previous, next.

Does that help at all? This seems like such a simple thing to do in Wordpress, or even Drupal using Views, but twig is just fighting me.

0
votes

You can use https://www.drupal.org/project/kint

e.g

{{ kint(data) }}

This way you can explore the arrays and objects inside that variable.

0
votes

Try this one :

{% for item in data.field_taxonomy %}
    {{ item.entity.label }}
{% endfor %}