我正在尝试使用 League\Commonmark 2.3.8 和 Drupal 中的扩展来渲染 markdown,当我尝试使用扩展进行渲染时,出现以下错误:
无法找到节点类型对应的渲染器 League\CommonMark\Node\Block\Document
这是我的代码:
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;
}
}
问题与我创建环境的方式有关。我知道这一点是因为我重写了 process() 如下,并且降价转换按预期工作:
public function process($text, $langcode): FilterProcessResult {
$converter = new CommonMarkConverter($this->config);
$converted_text = $converter->convert($text);
return new FilterProcessResult("$converted_text");
}
我还删除了所有 addExtension 行并得到了相同的错误,所以问题是 new Environment($this->config)。
然后我尝试在没有配置的情况下进行初始化:new Environment([]),但我仍然遇到相同的错误。
那么我做错了什么?
(Drupal 有一个 markdown 模块,但我无法使用它,因为我要将网站迁移到 Drupal 10 并且该模块不兼容。)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您还需要添加
CommonMarkCoreExtension或InlinesOnlyExtension,因为它们为Document、等内容提供解析器和渲染器>段落和文本节点。 (或者,如果您需要更多地控制要包含或排除的语法,您可以自己手动注册各个解析器和渲染器)。