Add abs filter
authorMaarten de Keizer <github@maartendekeizer.nl>
Sat, 26 May 2012 18:45:50 +0000 (20:45 +0200)
committerMaarten de Keizer <github@maartendekeizer.nl>
Mon, 28 May 2012 20:27:26 +0000 (22:27 +0200)
including unit test and documentation

doc/filters/abs.rst [new file with mode: 0644]
lib/Twig/Extension/Core.php
test/Twig/Tests/Fixtures/filters/abs.test [new file with mode: 0644]

diff --git a/doc/filters/abs.rst b/doc/filters/abs.rst
new file mode 100644 (file)
index 0000000..3a82f62
--- /dev/null
@@ -0,0 +1,18 @@
+``abs``
+=======
+
+The ``abs`` filter returns the absolute value.
+
+.. code-block:: jinja
+
+    {# number = -5 #}
+    
+    {{ number|abs }}
+    
+    {# outputs 5 #}
+
+.. note::
+
+    Internally, Twig uses the PHP `abs`_ function.
+
+.. _`abs`: http://php.net/abs
index e72dc5e..32606a3 100644 (file)
@@ -126,6 +126,7 @@ class Twig_Extension_Core extends Twig_Extension
             'format'        => new Twig_Filter_Function('sprintf'),
             'replace'       => new Twig_Filter_Function('strtr'),
             'number_format' => new Twig_Filter_Function('twig_number_format_filter', array('needs_environment' => true)),
+            'abs'           => new Twig_Filter_Function('abs'),
 
             // encoding
             'url_encode'       => new Twig_Filter_Function('twig_urlencode_filter'),
diff --git a/test/Twig/Tests/Fixtures/filters/abs.test b/test/Twig/Tests/Fixtures/filters/abs.test
new file mode 100644 (file)
index 0000000..27e93fd
--- /dev/null
@@ -0,0 +1,30 @@
+--TEST--
+"abs" filter
+--TEMPLATE--
+{{ (-5.5)|abs }}
+{{ (-5)|abs }}
+{{ (-0)|abs }}
+{{ 0|abs }}
+{{ 5|abs }}
+{{ 5.5|abs }}
+{{ number1|abs }}
+{{ number2|abs }}
+{{ number3|abs }}
+{{ number4|abs }}
+{{ number5|abs }}
+{{ number6|abs }}
+--DATA--
+return array('number1' => -5.5, 'number2' => -5, 'number3' => -0, 'number4' => 0, 'number5' => 5, 'number6' => 5.5)
+--EXPECT--
+5.5
+5
+0
+0
+5
+5.5
+5.5
+5
+0
+0
+5
+5.5