blob: 80145df5ef98cc93cd55b206c21e36a8dcba24e5 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001``html_to_markdown``
2====================
3
4The ``html_to_markdown`` filter converts a block of HTML to Markdown:
5
6.. code-block:: html+twig
7
8 {% apply html_to_markdown %}
9 <html>
10 <h1>Hello!</h1>
11 </html>
12 {% endapply %}
13
14You can also use the filter on an entire template which you ``include``:
15
16.. code-block:: twig
17
18 {{ include('some_template.html.twig')|html_to_markdown }}
19
20.. note::
21
22 The ``html_to_markdown`` filter is part of the ``MarkdownExtension`` which
23 is not installed by default. Install it first:
24
25 .. code-block:: bash
26
27 $ composer require twig/markdown-extra
28
29 On Symfony projects, you can automatically enable it by installing the
30 ``twig/extra-bundle``:
31
32 .. code-block:: bash
33
34 $ composer require twig/extra-bundle
35
36 Or add the extension explicitly on the Twig environment::
37
38 use Twig\Extra\Markdown\MarkdownExtension;
39
40 $twig = new \Twig\Environment(...);
41 $twig->addExtension(new MarkdownExtension());
42
43 If you are not using Symfony, you must also register the extension runtime::
44
45 use Twig\Extra\Markdown\DefaultMarkdown;
46 use Twig\Extra\Markdown\MarkdownRuntime;
47 use Twig\RuntimeLoader\RuntimeLoaderInterface;
48
49 $twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
50 public function load($class) {
51 if (MarkdownRuntime::class === $class) {
52 return new MarkdownRuntime(new DefaultMarkdown());
53 }
54 }
55 });
56
57``html_to_markdown`` is just a frontend; the actual conversion is done by one of
58the following compatible libraries, from which you can choose:
59
60* `erusev/parsedown`_
61* `league/html-to-markdown`_
62* `michelf/php-markdown`_
63
64Depending on the library, you can also add some options by passing them as an argument
65to the filter. Example for ``league/html-to-markdown``:
66
67.. code-block:: html+twig
68
69 {% apply html_to_markdown({hard_break: false}) %}
70 <html>
71 <h1>Hello!</h1>
72 </html>
73 {% endapply %}
74
75.. _erusev/parsedown: https://github.com/erusev/parsedown
76.. _league/html-to-markdown: https://github.com/thephpleague/html-to-markdown
77.. _michelf/php-markdown: https://github.com/michelf/php-markdown