Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``inline_css`` |
| 2 | ============== |
| 3 | |
| 4 | The ``inline_css`` filter inline CSS styles in HTML documents: |
| 5 | |
| 6 | .. code-block:: html+twig |
| 7 | |
| 8 | {% apply inline_css %} |
| 9 | <html> |
| 10 | <head> |
| 11 | <style> |
| 12 | p { color: red; } |
| 13 | </style> |
| 14 | </head> |
| 15 | <body> |
| 16 | <p>Hello CSS!</p> |
| 17 | </body> |
| 18 | </html> |
| 19 | {% endapply %} |
| 20 | |
| 21 | You can also add some stylesheets by passing them as arguments to the filter: |
| 22 | |
| 23 | .. code-block:: html+twig |
| 24 | |
| 25 | {% apply inline_css(source("some_styles.css"), source("another.css")) %} |
| 26 | <html> |
| 27 | <body> |
| 28 | <p>Hello CSS!</p> |
| 29 | </body> |
| 30 | </html> |
| 31 | {% endapply %} |
| 32 | |
| 33 | Styles loaded via the filter override the styles defined in the ``<style>`` tag |
| 34 | of the HTML document. |
| 35 | |
| 36 | You can also use the filter on an included file: |
| 37 | |
| 38 | .. code-block:: twig |
| 39 | |
| 40 | {{ include('some_template.html.twig')|inline_css }} |
| 41 | |
| 42 | {{ include('some_template.html.twig')|inline_css(source("some_styles.css")) }} |
| 43 | |
| 44 | Note that the CSS inliner works on an entire HTML document, not a fragment. |
| 45 | |
| 46 | .. note:: |
| 47 | |
| 48 | The ``inline_css`` filter is part of the ``CssInlinerExtension`` which is not |
| 49 | installed by default. Install it first: |
| 50 | |
| 51 | .. code-block:: bash |
| 52 | |
| 53 | $ composer require twig/cssinliner-extra |
| 54 | |
| 55 | Then, on Symfony projects, install the ``twig/extra-bundle``: |
| 56 | |
| 57 | .. code-block:: bash |
| 58 | |
| 59 | $ composer require twig/extra-bundle |
| 60 | |
| 61 | Otherwise, add the extension explicitly on the Twig environment:: |
| 62 | |
| 63 | use Twig\Extra\CssInliner\CssInlinerExtension; |
| 64 | |
| 65 | $twig = new \Twig\Environment(...); |
| 66 | $twig->addExtension(new CssInlinerExtension()); |