slider-block.html.twig

The above template shows me the title field for each Slides node, which is what I expect. The problem is that if I un-publish a Slides node, the markup is not updated unless I clear caches.

Alright, this sounds like a cache issue, so I dove into a google search mission and discovered a series of ways to disable caching for the block. None of which seem to work, for anonymous users or otherwise:

I looked at cache contexts, as far as I could tell, there was no 'node' based cache context. If I understood them correctly, cache tags wouldn't help, since I don't know the ids of any given node of type 'Slides'.

I 'only want to' disable caching for this block. This block will be rendered only on a specific page, so I could disable caching on that page using the modules route yml file (am I right?), but it feels wrong to disable that whole page for the sake of one block.

What is the right way to solve this, and what's the methodology in reaching that conclusion?

Note: I could use views to collect the nodes, but to customise the view markup is more challenging.

Adding a tag of node_list would do it, but it would also invalidate the cache when any node was created or updated, not just ones that would be involved in the slider. If you need to get more granular, use your own custom cache tag, and implement hook_node_insert etc to invalidate it under the right conditions (probably content type == slider)
– Clive♦Jan 20 at 11:18

@leymannx I think there's a core issue open for it somewhere. There's also Handy cache tags which provides it. But I hate to add another module for something that can be done in a few lines of code ;)
– Clive♦Jan 20 at 11:41

As mentioned on the comments by @Clive and @leymannx, you need to use cache tags to do the job. The problem is with your current approach will be tricky since your nodes are being loaded by your theme hook. Would be much cleaner and Drupal-way of doing things if you refactor your code and make your nodes loaded by the block, so your theme hook can focus on his work: prepare data and render it. Your code could be as follow (dependency injects ommited on purpose, please read more about this here):

As a side note, getCacheTags() is only in case if you don't return a rendered result, as explained above the code in the linked post, otherwise the build array should contain the cache tags.
– 4k4Jan 20 at 16:55

Duly noted, but the template provided by the OP does no render the entities only prints out their label in plain text so we could use the cache tags. But I think your answer is more efficient and I wasn't aware of this change, is indeed a handy tool.
– d70rr3sJan 20 at 22:25

My side note is not about individual tags vs list tags, it's about where to add cache metadata in general, and this should be the render array when you have a render array. See why this can be an issue drupal.stackexchange.com/questions/288881/…
– 4k4Jan 20 at 23:09