Browse code

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

Fabien Potencier authored on 17/03/2012 11:42:06
Showing 3 changed files
... ...
@@ -1,5 +1,6 @@
1 1
 * 1.7.0 (2012-XX-XX)
2 2
 
3
+ * added preserveKeys support for the slice filter
3 4
  * fixed the date filter when a DateTime instance is passed with a specific timezone
4 5
  * added a trim filter
5 6
 
... ...
@@ -559,21 +559,22 @@ function twig_array_merge($arr1, $arr2)
559 559
 /**
560 560
  * Slices a variable.
561 561
  *
562
- * @param Twig_Environment $env    A Twig_Environment instance
563
- * @param mixed            $item   A variable
564
- * @param integer          $start  Start of the slice
565
- * @param integer          $length Size of the slice
562
+ * @param Twig_Environment $env          A Twig_Environment instance
563
+ * @param mixed            $item         A variable
564
+ * @param integer          $start        Start of the slice
565
+ * @param integer          $length       Size of the slice
566
+ * @param Boolean          $preserveKeys Whether to preserve key or not (when the input is an array)
566 567
  *
567 568
  * @return mixed The sliced variable
568 569
  */
569
-function twig_slice(Twig_Environment $env, $item, $start, $length = null)
570
+function twig_slice(Twig_Environment $env, $item, $start, $length = null, $preserveKeys = false)
570 571
 {
571 572
     if ($item instanceof Traversable) {
572 573
         $item = iterator_to_array($item, false);
573 574
     }
574 575
 
575 576
     if (is_array($item)) {
576
-        return array_slice($item, $start, $length);
577
+        return array_slice($item, $start, $length, $preserveKeys);
577 578
     }
578 579
 
579 580
     $item = (string) $item;
... ...
@@ -5,7 +5,10 @@
5 5
 {{ {a: 1, b: 2, c: 3, d: 4}[1:2]|join('') }}
6 6
 {{ [1, 2, 3, 4][start:length]|join('') }}
7 7
 {{ [1, 2, 3, 4]|slice(1, 2)|join('') }}
8
+{{ [1, 2, 3, 4]|slice(1, 2)|keys|join('') }}
9
+{{ [1, 2, 3, 4]|slice(1, 2, true)|keys|join('') }}
8 10
 {{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|join('') }}
11
+{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|keys|join('') }}
9 12
 {{ '1234'|slice(1, 2) }}
10 13
 {{ '1234'[1:2] }}
11 14
 {{ arr|slice(1, 2)|join('') }}
... ...
@@ -22,7 +25,10 @@ return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3
22 25
 23
23 26
 23
24 27
 23
28
+01
29
+12
25 30
 23
31
+bc
26 32
 23
27 33
 23
28 34
 23