This is an example Drupal module on how to create your own custom context providers and how to use them in your projects. This is suitable for Drupal 9 and 10.
The following context providers are available:
Looks up the user's IP address.
Located in class \Drupal\custom_contexts\ContextProvider\IpAddressContext.
Generates a random IP address.
Located in class \Drupal\custom_contexts\ContextProvider\RandomIpAddressContext.
Loads a random published node from the database.
Located in class \Drupal\custom_contexts\ContextProvider\NodeRandomContext.
Loads a node referenced from the route node through the field field_referenced_article.
Located in class \Drupal\custom_contexts\ContextProvider\ReferencedNodeContext.
Example context provider showing how to return multiple values.
Located in class \Drupal\custom_contexts\ContextProvider\MultipleStringContext.
The following example blocks are available:
Shows the users IP address using the IP Address context provider.
Located in class \Drupal\custom_contexts\Plugin\Block\IpContextBlock.
Shows how to load a node through the context provider.
Located in class \Drupal\custom_contexts\Plugin\Block\NodeContextBlock.
Show how to load a user through the context provider.
Located in class \Drupal\custom_contexts\Plugin\Block\UserContextBlock.
A page at /block-page was created to show how to inject a block into a controller along with the context for the block.
This is provided by the controller at \Drupal\custom_contexts\Controller\TestController.
A sub-module exists called context_aware_plugin. This module defines a custom plugin called ContextThing that is context aware. A page is created at /context-thing-page that will render the output from the plugin.
For more information on this please see the following articles: