How do I see which contexts are active on the page?
I can't find any ContextManager
object in hook_preprocess_page()
.
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI figured it out: The Context module defines a service for getting the ContextManager
object, which has getActiveContexts()
. You can obtain it using the following code.
$activeContexts = \Drupal::service('context.manager')->getActiveContexts();
I need to read Service Container.
You can use this snippet in template_preprocess_page():
// Pass vars to page.html.twig depending on active contexts
$active_contexts = \Drupal::service('context.manager')->getActiveContexts();
$vars['is_my_context_active'] = FALSE;
foreach ($active_contexts as $context) {
if ($context->getName() == 'my_context') {
$vars['is_my_context_active'] = TRUE;
break;
}
}