From: fabien Date: Sun, 13 Dec 2009 12:40:43 +0000 (+0000) Subject: added the in filter X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=5a49c956bfb0320a7e3a3799c01c3fb2dd6a6cef;p=konrad%2Ftwig.git added the in filter git-svn-id: http://svn.twig-project.org/trunk@167 93ef8e89-cb99-4229-a87c-7fa0fa45744b --- diff --git a/CHANGELOG b/CHANGELOG index 0299039..c5ded3d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 0.9.5-DEV + * added the following filters in the Core extension: in * added support for arrays (same behavior as in PHP, a mix between lists and dictionaries, arrays and hashes) * enhanced some error messages to provide better feedback in case of parsing errors diff --git a/doc/02-Twig-for-Template-Designers.markdown b/doc/02-Twig-for-Template-Designers.markdown index 585c07d..cac3278 100644 --- a/doc/02-Twig-for-Template-Designers.markdown +++ b/doc/02-Twig-for-Template-Designers.markdown @@ -832,6 +832,20 @@ the length of a string. The `sort` filter sorts an array. +### `in` + +Returns true if the value is contained within another one. + + [twig] + {# returns true #} + + {{ 1|in([1, 2, 3]) }} + + {{ 'cd'|in('abcde') }} + +You can use this filter to perform a containment test on strings, arrays, or +objects implementing the `ArrayAccess` interface. + ### `default` The `default` filter returns the passed default value if the value is diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index e93e08f..37c2c7a 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -84,6 +84,7 @@ class Twig_Extension_Core extends Twig_Extension 'reverse' => array('twig_reverse_filter', false), 'length' => array('twig_length_filter', false), 'sort' => array('twig_sort_filter', false), + 'in' => array('twig_in_filter', false), // iteration and runtime 'default' => array('twig_default_filter', false), diff --git a/lib/Twig/runtime.php b/lib/Twig/runtime.php index 4df8d41..4d98244 100644 --- a/lib/Twig/runtime.php +++ b/lib/Twig/runtime.php @@ -87,6 +87,24 @@ function twig_sort_filter($array) return $array; } +function twig_in_filter($value, $compare) +{ + if (is_array($compare)) + { + return in_array($value, $compare); + } + elseif (is_string($compare)) + { + return false !== strpos($compare, (string) $value); + } + elseif (is_object($compare) && $compare instanceof ArrayAccess) + { + return in_array($value, iterator_to_array($compare)); + } + + return false; +} + /* * Each type specifies a way for applying a transformation to a string * The purpose is for the string to be "escaped" so it is suitable for