added the in filter
authorfabien <fabien@93ef8e89-cb99-4229-a87c-7fa0fa45744b>
Sun, 13 Dec 2009 12:40:43 +0000 (12:40 +0000)
committerfabien <fabien@93ef8e89-cb99-4229-a87c-7fa0fa45744b>
Sun, 13 Dec 2009 12:40:43 +0000 (12:40 +0000)
git-svn-id: http://svn.twig-project.org/trunk@167 93ef8e89-cb99-4229-a87c-7fa0fa45744b

CHANGELOG
doc/02-Twig-for-Template-Designers.markdown
lib/Twig/Extension/Core.php
lib/Twig/runtime.php

index 0299039..c5ded3d 100644 (file)
--- 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
 
index 585c07d..cac3278 100644 (file)
@@ -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
index e93e08f..37c2c7a 100644 (file)
@@ -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),
index 4df8d41..4d98244 100644 (file)
@@ -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