Added "split" filter aka explode.

This commit is contained in:
Tyler King
2012-02-04 17:01:37 -03:30
committed by Konstantin G Romanov
parent 657de7bdeb
commit e3c201ad55
4 changed files with 62 additions and 0 deletions
+1
View File
@@ -18,6 +18,7 @@ Filters
lower
striptags
join
split
reverse
length
sort
+16
View File
@@ -0,0 +1,16 @@
``split``
========
The ``split`` filter returns a list of items from a string that's separated by the provided delimiter or glue:
.. code-block:: jinja
{{ "one,two,three"|split(',') }}
{# returns [one, two, three] #}
A limit parameter is available which the returned list will contain a maximum of limit elements with the last element containing the rest of string.
.. code-block:: jinja
{{ "one,two,three,four,five"|split(',', 3) }}
{# returns [one, two, "three,four,five"] #}
+33
View File
@@ -145,6 +145,7 @@ class Twig_Extension_Core extends Twig_Extension
// array helpers
'join' => new Twig_Filter_Function('twig_join_filter'),
'split' => new Twig_Filter_Function('twig_split_filter'),
'sort' => new Twig_Filter_Function('twig_sort_filter'),
'merge' => new Twig_Filter_Function('twig_array_merge'),
@@ -650,6 +651,38 @@ function twig_join_filter($value, $glue = '')
return implode($glue, (array) $value);
}
/**
* Splits the values into an array.
*
* The second parameter is option for the limit.
*
* <pre>
* {{ "one,two,three"|split(',') }}
* {# returns [one, two, three] #}
*
* {{ "one,two,three,four,five"|split(',', 3) }}
* {# returns [one, two, "three,four,five"] #}
* </pre>
*
* @param string $value A string
* @param string $delimiter The separator to explode by
* @param integer $limit The limit
*
* @return string The explode'ed string
*/
function twig_split_filter($value, $delimiter, $limit = null)
{
if (is_empty($delimiter)) {
throw new Twig_Error_Runtime('The string to split must be provided with a delimiter.');
}
if (!is_null($limit)) {
return explode($delimiter, $value, $limit);
}
return explode($delimiter, $value);
}
// The '_default' filter is used internally to avoid using the ternary operator
// which costs a lot for big contexts (before PHP 5.4). So, on average,
// a function call is cheaper.
@@ -0,0 +1,12 @@
--TEST--
"split" filter
--TEMPLATE--
{{ "one,two,three,four,five"|split(',')|join('-') }}
{{ foo|split(',')|join('-') }}
{{ bar|split(',', 3)|join('-') }}
--DATA--
return array('foo' => "one,two,three,four,five", 'bar' => "one,two,three,four,five")
--EXPECT--
one-two-three-four-five
one-two-three-four-five
one-two-three,four,five