Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``spaceless`` |
| 2 | ============= |
| 3 | |
| 4 | Use the ``spaceless`` filter to remove whitespace *between HTML tags*, not |
| 5 | whitespace within HTML tags or whitespace in plain text: |
| 6 | |
| 7 | .. code-block:: html+twig |
| 8 | |
| 9 | {{ |
| 10 | "<div> |
| 11 | <strong>foo</strong> |
| 12 | </div> |
| 13 | "|spaceless }} |
| 14 | |
| 15 | {# output will be <div><strong>foo</strong></div> #} |
| 16 | |
| 17 | You can combine ``spaceless`` with the ``apply`` tag to apply the transformation |
| 18 | on large amounts of HTML: |
| 19 | |
| 20 | .. code-block:: html+twig |
| 21 | |
| 22 | {% apply spaceless %} |
| 23 | <div> |
| 24 | <strong>foo</strong> |
| 25 | </div> |
| 26 | {% endapply %} |
| 27 | |
| 28 | {# output will be <div><strong>foo</strong></div> #} |
| 29 | |
| 30 | This tag is not meant to "optimize" the size of the generated HTML content but |
| 31 | merely to avoid extra whitespace between HTML tags to avoid browser rendering |
| 32 | quirks under some circumstances. |
| 33 | |
| 34 | .. caution:: |
| 35 | |
| 36 | As the filter uses a regular expression behind the scenes, its performance |
| 37 | is directly related to the text size you are working on (remember that |
| 38 | filters are executed at runtime). |
| 39 | |
| 40 | .. tip:: |
| 41 | |
| 42 | If you want to optimize the size of the generated HTML content, gzip |
| 43 | compress the output instead. |
| 44 | |
| 45 | .. tip:: |
| 46 | |
| 47 | If you want to create a tag that actually removes all extra whitespace in |
| 48 | an HTML string, be warned that this is not as easy as it seems to be |
| 49 | (think of ``textarea`` or ``pre`` tags for instance). Using a third-party |
| 50 | library like Tidy is probably a better idea. |
| 51 | |
| 52 | .. tip:: |
| 53 | |
| 54 | For more information on whitespace control, read the |
| 55 | :ref:`dedicated section <templates-whitespace-control>` of the documentation and learn how |
| 56 | you can also use the whitespace control modifier on your tags. |