Conditional Custom Text Filter plugin I have created a custom text filter plugin by extending FilterBase class. The process() function looks like

 public function process($text, $langcode) {
    // Get the current node to determine if it has the glossary field and if
    // that field is enabled.
    $node = \Drupal::routeMatch()-&gt;getParameter('node');
    if ($node &amp;&amp; $node-&gt;hasField('field_glossary') &amp;&amp; $node-&gt;field_glossary-&gt;value) {

      // Get all the terms in the Glossary vocabulary.
      $terms = $this-&gt;getTerms('glossary');

      // Make all the replacements.
      $new_text = $this-&gt;doReplace($text, $terms);

      // Create a filtered text object with the updated text.
      $result = new FilterProcessResult($new_text);
      return $result;
    }
    else {
      // Don't do the replacement.
      $result = new FilterProcessResult($text);
      return $result;
    }
  }


I am letting editor to choose to turn off/on text filtering via plugin by creating a flag field as used in code $node-&gt;field_glossary-&gt;value. The problem comes when I need to check the field value on non-node page, as on node page I can get the node object and check the value but for other entites like blocks how can I get the source entity for text?
That's not so easy, because the filter is normally not aware from which field it is called from.

The token filter module does this trick:

/**
 * Implements hook_preprocess_HOOK().
 */
function token_filter_preprocess_field(&amp;$variables) {
  if (isset($variables['element']['#object']) &amp;&amp; $variables['element']['#object'] instanceof ContentEntityInterface) {
    $entity = &amp;drupal_static('token_filter_entity');
    $entity = $variables['element']['#object'];
  }
}


The parent entity of the field is stored in a static variable and can be used in the filter:

  public function process($text, $langcode) {
    $entity = drupal_static('token_filter_entity', NULL);
    if (!is_null($entity) &amp;&amp; $entity instanceof ContentEntityInterface) {
      // use entity
    }
  }


http://cgit.drupalcode.org/token_filter/tree/token_filter.module?h=8.x-1.x

This may not be the best solution for most cases. If possible look for a better place for the code where you have direct access to the entity. For example in hook_entity_view_alter().