无法将 "markdown_to_html" 过滤器添加到树枝

Can't add "markdown_to_html" filter to twig

我想使用 markdown_to_html 过滤器在我的模板中呈现 makrdown,因此我尝试按照文档中的 instructions 进行操作,但过滤器未正确添加。我在渲染模板时得到的错误是 Message: Unknown "markdown_to_html" filter.

这是我的代码:

// Load twig and the markdown extension

require_once "../vendor/autoload.php";
$loader = new \Twig\Loader\FilesystemLoader("../templates");
$twig = new \Twig\Environment($loader, [
  "cache" => "../cache/twig",
  "debug" => true,
  "autoescape" => false,
]);

use Twig\Extra\Markdown\DefaultMarkdown;
use Twig\Extra\Markdown\MarkdownRuntime;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

$twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
  public function load($class) {
    if (MarkdownRuntime::class === $class) {
      return new MarkdownRuntime(new DefaultMarkdown());
    }
  }
});

// Read md file and render template

$markdown = file_get_contents("content/text.md");
try {
  echo $twig->render("template.phtml", ["text" => $markdown]);
}
catch(Exception $e) {
  echo 'Message: ' . $e->getMessage();
}


模板:

  {% apply markdown_to_html %}
    {{ text }}
  {% endapply %}

我添加了twig/twigtwig/markdown-extra,都是3.0版本。感谢您的帮助。

您忘记添加扩展名

$twig->addExtension(new MarkdownExtension());

注意文档怎么说

If you are not using Symfony, you must also register the extension runtime:

你这样做的时候而不是