php - 无法将“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/twig
and twig/markdown-extra
,都是版本3.0
。谢谢你的帮助。
解决方案
您忘记添加扩展名
$twig->addExtension(new MarkdownExtension());
请注意文档是如何说的
如果您不使用 Symfony,您还必须注册扩展运行时:
当你这样做的时候
推荐阅读
- go - 创建专用函数是处理错误的好方法吗
- excel - 如何为值范围和excel中的匹配条件执行If()
- javascript - 如何在 JavaScript 中创建 JSON 对象?
- python - 模块中定义的所有类的类型提示
- r - 使用 mutate()/case_when() 时出现奇怪的错误消息
- rpm - 在没有 root 权限的情况下在 HPC 集群(Centos 8)中安装 RPM 文件
- javascript - 更改一些代码格式(angularJS 到 javascript)
- button - STM32F070 EXTI(n) 误触发
- tensorflow - 多实例学习的可变实例数
- javascript - react native:如何修复错误 - 传递内联函数会导致组件状态在重新渲染时丢失?