No renderer found for node type: League\Commonmark + Drupal
P粉144705065
P粉144705065 2024-01-16 13:52:24
0
1
448

I'm trying to render markdown using League\Commonmark 2.3.8 and the extension in Drupal, when I try to render using the extension I get the following error:

Cannot find the renderer corresponding to the node type League\CommonMark\Node\Block\Document

This is 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 create the environment. I know this because I overridden process() as follows, and the 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 addExtension lines and got the same error, so the problem is new Environment($this->config).

Then I tried initializing without configuration: new Environment([]), but I still got the same error.

So what did I do wrong?

(Drupal has a markdown module, but I can't use it because I'm migrating the site to Drupal 10 and the module is not compatible.)

P粉144705065
P粉144705065

reply all(1)
P粉642920522

You will also need to add CommonMarkCoreExtension or InlinesOnlyExtension as they provide parsers and renderers for Document, etc > Paragraph and Text nodes. (Alternatively, if you need more control over which grammars are included or excluded, you can manually register individual parsers and renderers yourself).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template