Twig

灵活、快速和安全
PHP 模板引擎

a Symfony Product
文档 过滤器 html_to_markdown
您正在阅读 Twig 3.x 的文档。切换到 Twig 1.x, 2.x 的文档。

问题和反馈

许可证

Twig 文档基于新 BSD 许可证获得许可。

html_to_markdown

html_to_markdown 过滤器将 HTML 代码块转换为 Markdown

1
2
3
4
5
{% apply html_to_markdown %}
    <html>
        <h1>Hello!</h1>
    </html>
{% endapply %}

您也可以在您 include 的整个模板上使用此过滤器

1
{{ include('some_template.html.twig')|html_to_markdown }}

注意

html_to_markdown 过滤器是 MarkdownExtension 的一部分,默认情况下未安装。请先安装它

1
$ composer require twig/markdown-extra

在 Symfony 项目中,您可以通过安装 twig/extra-bundle 自动启用它

1
$ composer require twig/extra-bundle

或者在 Twig 环境中显式添加扩展

1
2
3
4
use Twig\Extra\Markdown\MarkdownExtension;

$twig = new \Twig\Environment(...);
$twig->addExtension(new MarkdownExtension());

如果您没有使用 Symfony,您还必须注册扩展运行时

1
2
3
4
5
6
7
8
9
10
11
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());
        }
    }
});

html_to_markdown 只是一个前端;实际的转换由以下兼容库之一完成,您可以从中选择

根据库的不同,您还可以通过将一些选项作为参数传递给过滤器来添加它们。例如 league/html-to-markdown

1
2
3
4
5
{% apply html_to_markdown({hard_break: false}) %}
    <html>
        <h1>Hello!</h1>
    </html>
{% endapply %}