diff --git a/src/Node/Expression/NullCoalesceExpression.php b/src/Node/Expression/NullCoalesceExpression.php index 49326d467..917d31a3b 100644 --- a/src/Node/Expression/NullCoalesceExpression.php +++ b/src/Node/Expression/NullCoalesceExpression.php @@ -22,11 +22,15 @@ class NullCoalesceExpression extends ConditionalExpression { public function __construct(\Twig_NodeInterface $left, \Twig_NodeInterface $right, $lineno) { - $test = new AndBinary( - new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine()), - new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), - $left->getTemplateLine() - ); + $test = new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine()); + // for "block()", we don't need the null test as the return value is always a string + if (!$left instanceof BlockReferenceExpression) { + $test = new AndBinary( + $test, + new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), + $left->getTemplateLine() + ); + } parent::__construct($test, $left, $right, $lineno); } diff --git a/tests/Fixtures/tests/null_coalesce_block.test b/tests/Fixtures/tests/null_coalesce_block.test new file mode 100644 index 000000000..73579140c --- /dev/null +++ b/tests/Fixtures/tests/null_coalesce_block.test @@ -0,0 +1,9 @@ +--TEST-- +Twig supports the ?? operator with blocks +--TEMPLATE-- +{% block foo %}OK{% endblock %} +{{ block('foo') ?? 'KO' }} +--DATA-- +return [] +--EXPECT-- +OKOK