#! code: Drupal 10: Using Context Definitions To Create Context Aware Plugins

When developing plugins in Drupal a common task is to inject context so that certain tasks can be performed.

For example, we might have a block plugin that needs to know about the content entity of the page it is currently being rendered on. We could potentially inject the routing system into the plugin and use this to find the currently loaded entity, but there is a drawback to this. There is a fair amount of custom logic involved in finding the content entity from the route and we would need to use this same code every time we want to solve this problem.

This method also hard codes the route into the plugin and so makes it difficult to select any other sort of context. There is also a problem when it comes to caching as you also need to inform the plugin about the use of routing so that the caching layers know how to cache things.

This is where context definitions come in. We can use this system to automatically inject context awareness into plugins and then select how that context is detected. This also takes care of the cache systems so we don't need to worry about that.

In this article I will go through using context definitions to detect different types of entities in a block and how caching is handled though context. I'll also show how to configure where the context comes from via the block configuration page.

Adding Context To A Block

Let's take a simple block that renders a field from a node entity. We can place this block onto the site, but it don't show anything as we don't currently have access to the node object.

Read more

PubDate

Tags