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