首页 > 解决方案 > 无法将“markdown_to_html”过滤器添加到树枝

问题描述

我想使用markdown_to_html过滤器在我的模板中呈现 makrdown,所以我尝试按照文档中的说明进行操作,但未正确添加过滤器。呈现模板时出现的错误是消息:未知的“markdown_to_html”过滤器。

这是我的代码:

// 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/twigand twig/markdown-extra,都是版本3.0。谢谢你的帮助。

标签: phptwigmarkdown

解决方案


您忘记添加扩展名

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

请注意文档是如何说的

如果您不使用 Symfony,您必须注册扩展运行时:

当你这样做的时候


推荐阅读