Document how to use block contexts

Created on 18 June 2018, almost 6 years ago
Updated 20 January 2024, 4 months ago

This might be overkill for the documentation, but in upgrading to 2.0 I ran into something that was not obvious (to me at least), so wanted to share it here and hopefully save others the time of figuring it out.

If you're using a block plugin that has a required context (in my case, a Table of Contents for a node), you need to supply a context mapping to tell the block instance where to get that context from. Otherwise, you end up with an error like:
Drupal\Component\Plugin\Exception\ContextException: Required contexts without a value: node. in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping()

Normally this context mapping gets set when you create a block config entity, but if you're using drupal_block() to render the block that obviously doesn't apply.

I found two ways to make it work.

In your twig template you can use something like:
{{ drupal_block('node_toc', {context_mapping: {node: '@node.node_route_context:node'}}) }}

Or in your block plugin you can include a method like this:

  /**
   * {@inheritdoc}
   */
  public function getContextMapping() {
    $mapping = parent::getContextMapping();
    // By default, get the node from the URL.
    return $mapping ?: ['node' => '@node.node_route_context:node'];
  }
πŸ“Œ Task
Status

Fixed

Version

3.0

Component

Documentation

Created by

πŸ‡ΊπŸ‡ΈUnited States JeffM2001

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024