the foo attribute really is the `false` PHP value
{% endif %}
-### `constant` (new in Twig 0.9.9)
+### `constant`
`constant` checks if a variable has the exact same value as a constant. You
can use either global constants or class constants:
the status attribute is exactly the same as Post::PUBLISHED
{% endif %}
+### `defined`
+
+`defined` checks if a variable is defined in the current context. This is very
+useful if you use the `strict_variables` option.
+
Extensions
----------
return array(
'even' => new Twig_Test_Function('twig_test_even'),
'odd' => new Twig_Test_Function('twig_test_odd'),
- //'defined' => new Twig_Test_Function(),
+ 'defined' => new Twig_Test_Function('twig_test_defined'),
'sameas' => new Twig_Test_Function('twig_test_sameas'),
'none' => new Twig_Test_Function('twig_test_none'),
'divisibleby' => new Twig_Test_Function('twig_test_divisibleby'),
{
return constant($constant) === $value;
}
+
+function twig_test_defined($name, $context)
+{
+ return array_key_exists($name, $context);
+}
throw new Twig_Error_Syntax(sprintf('The test "%s" does not exist', $this->getAttribute('name')), $this->getLine());
}
+ // defined is a special case
+ if ('defined' === $this->getAttribute('name')) {
+ if (!$this->getNode('node') instanceof Twig_Node_Expression_Name){
+ throw new Twig_Error_Syntax('The "defined" test only works with simple variables', $this->getLine());
+ }
+
+ $compiler
+ ->raw($testMap[$this->getAttribute('name')]->compile().'(')
+ ->repr($this->getNode('node')->getAttribute('name'))
+ ->raw(', $context)')
+ ;
+
+ return;
+ }
+
$compiler
->raw($testMap[$this->getAttribute('name')]->compile().'(')
->subcompile($this->getNode('node'))