From: Fabien Potencier Date: Wed, 29 Jan 2014 08:45:07 +0000 (+0100) Subject: added a note about how to check for dynamic attribute existence in the docs X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=e9e474847542bd30c394c6aca81a04ea7bc0a5b3;p=konrad%2Ftwig.git added a note about how to check for dynamic attribute existence in the docs --- diff --git a/doc/functions/attribute.rst b/doc/functions/attribute.rst index 3051bda..ceba96b 100644 --- a/doc/functions/attribute.rst +++ b/doc/functions/attribute.rst @@ -4,7 +4,8 @@ .. versionadded:: 1.2 The ``attribute`` function was added in Twig 1.2. -``attribute`` can be used to access a "dynamic" attribute of a variable: +The ``attribute`` function can be used to access a "dynamic" attribute of a +variable: .. code-block:: jinja @@ -12,6 +13,13 @@ {{ attribute(object, method, arguments) }} {{ attribute(array, item) }} +In addition, the ``defined`` test can check for the existence of a dynamic +attribute: + +.. code-block:: jinja + + {{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }} + .. note:: The resolution algorithm is the same as the one used for the ``.`` diff --git a/test/Twig/Tests/Fixtures/functions/attribute.test b/test/Twig/Tests/Fixtures/functions/attribute.test index 16ae1e8..472b74d 100644 --- a/test/Twig/Tests/Fixtures/functions/attribute.test +++ b/test/Twig/Tests/Fixtures/functions/attribute.test @@ -4,9 +4,13 @@ {{ attribute(obj, method) }} {{ attribute(array, item) }} {{ attribute(obj, "bar", ["a", "b"]) }} +{{ attribute(obj, method) is defined ? 'ok' : 'ko' }} +{{ attribute(obj, nonmethod) is defined ? 'ok' : 'ko' }} --DATA-- -return array('obj' => new TwigTestFoo(), 'method' => 'foo', 'array' => array('foo' => 'bar'), 'item' => 'foo') +return array('obj' => new TwigTestFoo(), 'method' => 'foo', 'array' => array('foo' => 'bar'), 'item' => 'foo', 'nonmethod' => 'xxx') --EXPECT-- foo bar bar_a-b +ok +ko