mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-05 23:17:26 +00:00
Add traversable test
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
``traversable``
|
||||
=========
|
||||
|
||||
``traversable`` checks if a variable is an array or a traversable object:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{# evaluates to true if the foo variable is traversable #}
|
||||
{% if foo is traversable %}
|
||||
...
|
||||
{% endif %}
|
||||
@@ -203,6 +203,7 @@ class Twig_Extension_Core extends Twig_Extension
|
||||
'constant' => new Twig_Test_Node('Twig_Node_Expression_Test_Constant'),
|
||||
'empty' => new Twig_Test_Function('twig_test_empty'),
|
||||
'array' => new Twig_Test_Function('is_array'),
|
||||
'traversable' => new Twig_Test_Function('twig_test_traversable'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1014,3 +1015,22 @@ function twig_test_empty($value)
|
||||
|
||||
return false === $value || (empty($value) && '0' != $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a variable is traversable.
|
||||
*
|
||||
* <pre>
|
||||
* {# evaluates to true if the foo variable is an array or a traversable object #}
|
||||
* {% if foo is traversable %}
|
||||
* {# ... #}
|
||||
* {% endif %}
|
||||
* </pre>
|
||||
*
|
||||
* @param mixed $value A variable
|
||||
*
|
||||
* @return Boolean true if the value is traversable
|
||||
*/
|
||||
function twig_test_traversable($value)
|
||||
{
|
||||
return is_array($value) || (is_object($value) && $value instanceof Traversable);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
--TEST--
|
||||
"traversable" test
|
||||
--TEMPLATE--
|
||||
{{ foo is traversable ? 'ok' : 'ko' }}
|
||||
{{ traversable is traversable ? 'ok' : 'ko' }}
|
||||
{{ obj is traversable ? 'ok' : 'ko' }}
|
||||
{{ val is traversable ? 'ok' : 'ko' }}
|
||||
--DATA--
|
||||
return array(
|
||||
'foo' => array(),
|
||||
'traversable' => new ArrayIterator(array()),
|
||||
'obj' => new stdClass(),
|
||||
'val' => 'test',
|
||||
);
|
||||
--EXPECT--
|
||||
ok
|
||||
ok
|
||||
ko
|
||||
ko
|
||||
Reference in New Issue
Block a user