4

How do I see which contexts are active on the page?

I can't find any ContextManager object in hook_preprocess_page().

3 Answers 3

4

I 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.

2

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;
    }
  }
0

We've experienced a similar problem with being not aware of which contexts are applied on a current page.

We created context_active_inspector module that also uses context.manager to find active contexts and represent them as toolbar bar with links to context admin interface (if context_ui module enabled).

We would appreciate if you give a try for it, if it fits your needs. The feedback is very welcome!

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.