Twig/Drupal caching and dynamic variables I have a template with a list of recent articles and an article itself. I want to check in the list of recent articles if the article currently viewed is there and if yes add a class to the div. This works all fine on a development environment but as soon as I turn on caching it goes haywire. The class is stuck on one item instead of switching to the active one.

How can I solve this? 

My template:

&lt;a class="news-block {{ node.id == current_id ? 'news-block--active' : '' }}" href="{{ url }}"&gt;
    ...
&lt;/a&gt;


My preprocess:

function theme_preprocess_article(array &amp;$variables) {
    $currentNode = \Drupal::routeMatch()-&gt;getParameter('node');
    $variables['current_id'] = $currentNode-&gt;get('nid')-&gt;getValue()[0]['value'];
}
My understanding is that this doesn't vary on the same URL, so both page_cache and dynamic_page_cache should be fine. However, each node is also cached on its own, a and that's your problem here.

As 4k4 said in the comment, you should be able to vary the cache with this: $variables['#cache']['contexts'][] = 'url'.

That's rather problematic however, because it means that every node needs to be cached differently on every page, which results in a huge amount of variations that fill up your cache tables.

You could define your own cache context for whether you are on the node page of a given node. Core actually should provide a cache context for that, since it has a similar problem when you'd e.g. use the default view mode somewhere else than on the node/N page. But it doesn't, there's an open issue for that.

As mentioned, the easiest fix is probably to use JS for this.