The problem I'm trying to solve is this: I need a unique (but human readable) class name to be able to style Taxonomy Term page depending on the term shown. I unsuccessfully tried several approaches, the nearest being this:
My views-view.html.twig excerpt:
{% set tid = view.argument["tid"].value[0] %}
HEREITIS:{{tid}}<br/>
{% set pathclass = path('entity.taxonomy_term.canonical', {'taxonomy_term': 48}) | replace({'/': '-'}) %}
{%
set classes = [
dom_id ? 'js-view-dom-id-' ~ dom_id,
tid,
pathclass,
]
%}
<div{{ attributes.addClass(classes) }}>
And it produces the result that I could almost work with:
<!-- 💡 BEGIN CUSTOM TEMPLATE OUTPUT from 'sites/bezdatu.test/themes/qq/templates/views/views-view.html.twig' -->
HEREITIS:48<br/>
<div class="view-taxonomy-term contextual-region js-view-dom-id-8549dd661... 48 -category-holiday">
Note that both numbers "48
" in the result come from tid
variable and "-category-holiday
" is correctly calculated based on the hardcoded "48
" number. "Hardcoded" however is the only working scenario and I'm at total loss as to why changing
path('entity.taxonomy_term.canonical', {'taxonomy_term': 48})
to
path('entity.taxonomy_term.canonical', {'taxonomy_term': tid})
results in "an unexpected error" saying that I'm passing an empty value:
The website encountered an unexpected error. Try again later.
Symfony\Component\Routing\Exception\InvalidParameterException: Parameter "taxonomy_term" for route "entity.taxonomy_term.canonical" must match "[^/]++" ("" given) to generate a corresponding URL. in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 202 of core/lib/Drupal/Core/Routing/UrlGenerator.php).
The variable is not empty, it is "48" and my only guess is that the twig template gets parsed before the variable value is calculated or view arguments become available. Is there any fix for this or any other simple approach to add path alias as css class name short of fiddling with javascript?
Maybe another view is also being rendered? One that is not the taxonomy view, but would still be using the views-view.html.twig template? Try renaming your template file to something more specific for the taxonomy view so the template is only used for that view.