added a spaceless filter

This commit is contained in:
Fabien Potencier
2019-03-07 08:06:13 +01:00
parent 1ba7941656
commit b823898ee1
5 changed files with 78 additions and 0 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.38.0 (2019-XX-XX)
* added a spaceless filter
* added max value to the "random" function
* made namespace classes the default classes (PSR-0 ones are aliases now)
* removed duplicated directory separator in FilesystemLoader
+54
View File
@@ -0,0 +1,54 @@
``spaceless``
=============
.. versionadded:: 1.38
The ``spaceless`` filter was added in Twig 1.38.
Use the ``spaceless`` filter to remove whitespace *between HTML tags*, not
whitespace within HTML tags or whitespace in plain text:
.. code-block:: jinja
{{
"<div>
<strong>foo</strong>
</div>
"|spaceless }}
{# output will be <div><strong>foo</strong></div> #}
You can combine ``spaceless`` with the ``filter`` tag to apply the
transformation on large amounts of HTML:
.. code-block:: jinja
{% filter spaceless %}
<div>
<strong>foo</strong>
</div>
{% endfilter %}
{# output will be <div><strong>foo</strong></div> #}
This tag is not meant to "optimize" the size of the generated HTML content but
merely to avoid extra whitespace between HTML tags to avoid browser rendering
quirks under some circumstances.
.. tip::
If you want to optimize the size of the generated HTML content, gzip
compress the output instead.
.. tip::
If you want to create a tag that actually removes all extra whitespace in
an HTML string, be warned that this is not as easy as it seems to be
(think of ``textarea`` or ``pre`` tags for instance). Using a third-party
library like Tidy is probably a better idea.
.. tip::
For more information on whitespace control, read the
:ref:`dedicated section <templates-whitespace-control>` of the documentation and learn how
you can also use the whitespace control modifier on your tags.
+4
View File
@@ -1,6 +1,10 @@
``spaceless``
=============
.. tip::
As of Twig 1.38, use the :doc:`spaceless <../filters/spaceless>` filter instead.
Use the ``spaceless`` tag to remove whitespace *between HTML tags*, not
whitespace within HTML tags or whitespace in plain text:
+11
View File
@@ -184,6 +184,7 @@ class CoreExtension extends AbstractExtension
new TwigFilter('striptags', 'strip_tags'),
new TwigFilter('trim', 'twig_trim_filter'),
new TwigFilter('nl2br', 'nl2br', ['pre_escape' => 'html', 'is_safe' => ['html']]),
new TwigFilter('spaceless', 'twig_spaceless', ['is_safe' => ['html']]),
// array helpers
new TwigFilter('join', 'twig_join_filter'),
@@ -988,6 +989,16 @@ function twig_trim_filter($string, $characterMask = null, $side = 'both')
}
}
/**
* Removes whitespaces between HTML tags.
*
* @return string
*/
function twig_spaceless($content)
{
return preg_replace('/>\s+</', '><', $content);
}
/**
* Escapes a string.
*
@@ -0,0 +1,8 @@
--TEST--
"spaceless" filter
--TEMPLATE--
{{ " <div> <div> foo </div> </div>"|spaceless }}
--DATA--
return []
--EXPECT--
<div><div> foo </div></div>