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粉6429205222024-01-17 10:19:19
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).