League\Commonmark + Drupal: Unable to find corresponding renderer for node type

415 views Asked by At

I'm trying to render markdown using League\Commonmark 2.3.8 with extensions in Drupal and I'm getting the following error when I try to render with extensions:

Unable to find corresponding renderer for node type League\CommonMark\Node\Block\Document

Here's my code:

class FilterMarkdown extends FilterBase {

  /**
   * @var array The private config array.
   *
   * https://commonmark.thephpleague.com/2.3/configuration/.
   */
  private array $config = [
    // Allow because only the admin has markdown access.
    'html_input' => 'allow',
    'allow_unsafe_links' => false,
  ];

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode): FilterProcessResult {
    $converter = new MarkdownConverter($this->createEnvironment());

    $converted_text = $converter->convert($text);

    return new FilterProcessResult("$converted_text");
  }

  /**
   * Generate an environment with all the extensions we need.
   */
  private function createEnvironment(): Environment {
    $environment = new Environment($this->config);
    $environment->addExtension(new ExternalLinkExtension());
    $environment->addExtension(new HeadingPermalinkExtension());
    $environment->addExtension(new StrikethroughExtension());
    $environment->addExtension(new TableExtension());

    return $environment;
  }

}

The problem is related to the way I am creating the environment. I know this because I rewrote process() as follows and markdown conversion works as expected:

  public function process($text, $langcode): FilterProcessResult {
    $converter = new CommonMarkConverter($this->config);

    $converted_text = $converter->convert($text);

    return new FilterProcessResult("$converted_text");
  }

I also removed all the addExtension lines and got the same error, so the problem is new Environment($this->config).

I then tried initializing with no config: new Environment([]), but I still get the same error.

So what am I doing wrong?

(Drupal has a markdown module, but I can't use it because I am moving my site to Drupal 10 and the module isn't compatible.)

1

There are 1 answers

0
Colin O'Dell On BEST ANSWER

You'll need to also add the CommonMarkCoreExtension or InlinesOnlyExtension too as those provide the parsers and renderers for things like Document, Paragraph, and Text nodes. (Alternatively you could manually register the individual parsers and renderers yourself if you need more control over what syntax you want to include or exclude).