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:

<a class="news-block {{ node.id == current_id ? 'news-block--active' : '' }}" href="{{ url }}">

My preprocess:

function theme_preprocess_article(array &$variables) {
    $currentNode = \Drupal::routeMatch()->getParameter('node');
    $variables['current_id'] = $currentNode->get('nid')->getValue()[0]['value'];
  • Either do it with JS, or disable page_cache module(for anonymous), or add #cache configuration into the render array(for logged in users).
    – user21641
    Commented Jan 12, 2016 at 14:44
  • Seriously? Editing the #cache didn't work and disabling the page_cache will be an performance issue. I guess it's JS then.
    – Edwin
    Commented Jan 12, 2016 at 14:50
  • #cache will have no effect for anonymous users since page_cache module caches the whole pages, whereas dynamic_page_cache caches only parts of pages based on the #cache configuration, but for logged in users only. It depends on your use case. I have implements page cache policy where if certain cookie is present on anonymous user the page_cache is bypassed and dynamic_page_cache takes over.
    – user21641
    Commented Jan 12, 2016 at 15:11
  • Ahh! Do you have an example of editing the #cache configuration?
    – Edwin
    Commented Jan 12, 2016 at 15:18
  • 1
    Just search for #cache(for example core/modules/book/book.module:241)
    – user21641
    Commented Jan 12, 2016 at 15:34

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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