0

Original problem I had was I setup a taxonomy called Category. I added some vocabulary to my Category taxonomy. Some of the terms I added have contain spaces. The labels should have spaces so I want to keep them there. I want to remove the spaces from the Category name when they are output in the views view unformatted templated.

This would solve all of my problems if I can get those spaces out of the category names. I setup a custom field on the taxonomy terms to handle this, but I don't know how to access the custom fields of the taxonomy term from the views-view-unformatted.html.twig template. Is there a preprocesser function that can do this? Something where I can convert the category and just remove the spaces or change the value output from label to field_nospace_category ?

More experimenting

I setup a view of type page to display the articles in my content type Articles. I'm using using the unformatted list and I created a custom template called views-view-unformatted--my_view_id.html.twig. I see that this is the template that is outputting on my page.

I'm trying to output the taxonomy terms custom field as a class on the div that has {{ row.attributes.addClass(row_classes) }}

The div should end up looking like this:

...

I've tried several variations to try to get to the values. Inside of the for row in rows loop, i put:

{{ node.category.entity.field_category.value }}
{{ row.content['#node'].field_category.getValue().0.target_id }}
{{field_category}}
{{row.content['#elements'].field_category.getValue().0.target_id}}

I have tried to debug using Kint, Dump but my install keeps either throwing errors (out of memory) or blank white page.

Please help. Thank you in advance.

0

Finally got it to work! Here is how you do it. Assuming your field is called field_category. My template is called views-view-unformatted--my_view_id_name.html.twig.

{% set my_category_id = row.content['#row']._entity.field_category.0.target_id %}

It does seem pretty silly to me that it has to be that long. It would be very cool if it was something more like this and that all values associated to a post (since that is what is being output) are available and exposed to the view.

row.content.field_category.id

And if all taxonomies that are added would follow the same path. Seems unneccesary to have it in #row, then in _entity, then needing to add a 0 and use some oddly named thing called target_id.

I'm new to Drupal coming from Wordpress. There are nice clean functions in wordpress for getting taxonomy ID and names. Not too many hoops you need to jump through.

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.