From: Fabien Potencier Date: Tue, 8 Jan 2013 14:19:16 +0000 (+0100) Subject: added support for {{ some_string[:2] }} (closes #952) X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=d10ebfa3d4c16621732ebd8bcf65cd4cfdcefa26;p=web%2Fkonrad%2Ftwig.git added support for {{ some_string[:2] }} (closes #952) --- diff --git a/CHANGELOG b/CHANGELOG index cc1a820..3cf9005 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,6 @@ * 1.12.1 (2012-XX-XX) - * n/a + * added support for {{ some_string[:2] }} * 1.12.0 (2012-01-08) diff --git a/doc/filters/slice.rst b/doc/filters/slice.rst index 0205771..7a9ada0 100644 --- a/doc/filters/slice.rst +++ b/doc/filters/slice.rst @@ -34,6 +34,12 @@ As syntactic sugar, you can also use the ``[]`` notation: {{ '1234'[1:2] }} + {# you can omit the first argument -- which is the same as 0 #} + {{ '1234'[:2] }} {# will display "12" #} + + {# you can omit the last argument -- which will select everything till the end #} + {{ '1234'[2:] }} {# will display "34 #} + The ``slice`` filter works as the `array_slice`_ PHP function for arrays and `substr`_ for strings. diff --git a/lib/Twig/ExpressionParser.php b/lib/Twig/ExpressionParser.php index a330246..7b9114a 100644 --- a/lib/Twig/ExpressionParser.php +++ b/lib/Twig/ExpressionParser.php @@ -379,12 +379,21 @@ class Twig_ExpressionParser } else { $type = Twig_TemplateInterface::ARRAY_CALL; - $arg = $this->parseExpression(); - // slice? + $slice = false; + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ':')) { + $slice = true; + $arg = new Twig_Node_Expression_Constant(0, $token->getLine()); + } else { + $arg = $this->parseExpression(); + } + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ':')) { + $slice = true; $stream->next(); + } + if ($slice) { if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { $length = new Twig_Node_Expression_Constant(null, $token->getLine()); } else { diff --git a/test/Twig/Tests/Fixtures/filters/slice.test b/test/Twig/Tests/Fixtures/filters/slice.test index bb32dfb..b37ad65 100644 --- a/test/Twig/Tests/Fixtures/filters/slice.test +++ b/test/Twig/Tests/Fixtures/filters/slice.test @@ -18,6 +18,7 @@ {{ [1, 2, 3, 4][1:]|join('') }} {{ '1234'|slice(1) }} {{ '1234'[1:] }} +{{ '1234'[:1] }} --DATA-- return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3, 4))) --EXPECT-- @@ -38,3 +39,4 @@ bc 234 234 234 +1