added preserveKeys support for the slice filter (closes #669)

This commit is contained in:
Fabien Potencier
2012-03-17 12:42:06 +01:00
parent a3310e75a1
commit c0a9c8bb3e
3 changed files with 14 additions and 6 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.7.0 (2012-XX-XX)
* added preserveKeys support for the slice filter
* fixed the date filter when a DateTime instance is passed with a specific timezone
* added a trim filter
+7 -6
View File
@@ -559,21 +559,22 @@ function twig_array_merge($arr1, $arr2)
/**
* Slices a variable.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $item A variable
* @param integer $start Start of the slice
* @param integer $length Size of the slice
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $item A variable
* @param integer $start Start of the slice
* @param integer $length Size of the slice
* @param Boolean $preserveKeys Whether to preserve key or not (when the input is an array)
*
* @return mixed The sliced variable
*/
function twig_slice(Twig_Environment $env, $item, $start, $length = null)
function twig_slice(Twig_Environment $env, $item, $start, $length = null, $preserveKeys = false)
{
if ($item instanceof Traversable) {
$item = iterator_to_array($item, false);
}
if (is_array($item)) {
return array_slice($item, $start, $length);
return array_slice($item, $start, $length, $preserveKeys);
}
$item = (string) $item;
@@ -5,7 +5,10 @@
{{ {a: 1, b: 2, c: 3, d: 4}[1:2]|join('') }}
{{ [1, 2, 3, 4][start:length]|join('') }}
{{ [1, 2, 3, 4]|slice(1, 2)|join('') }}
{{ [1, 2, 3, 4]|slice(1, 2)|keys|join('') }}
{{ [1, 2, 3, 4]|slice(1, 2, true)|keys|join('') }}
{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|join('') }}
{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|keys|join('') }}
{{ '1234'|slice(1, 2) }}
{{ '1234'[1:2] }}
{{ arr|slice(1, 2)|join('') }}
@@ -22,7 +25,10 @@ return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3
23
23
23
01
12
23
bc
23
23
23