diff --git a/CHANGELOG b/CHANGELOG index 5fef904e97..dfe42fd75d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,6 @@ * 2.2.1 (2017-XX-XX) - * n/a + * added error message when calling `parent()` in a block that doesn't exist in the parent template * 2.2.0 (2017-02-26) diff --git a/lib/Twig/Template.php b/lib/Twig/Template.php index 46e6b3c0f9..ee9117e9d0 100644 --- a/lib/Twig/Template.php +++ b/lib/Twig/Template.php @@ -204,6 +204,8 @@ public function displayBlock($name, array $context, array $blocks = array(), $us } } elseif (false !== $parent = $this->getParent($context)) { $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks), false); + } elseif (isset($blocks[$name])) { + throw new Twig_Error_Runtime(sprintf('Block "%s" should not call parent() in "%s" as the block does not exist in the parent template "%s".', $name, $blocks[$name][0]->getTemplateName(), $this->getTemplateName()), -1, $blocks[$name][0]->getTemplateName()); } else { throw new Twig_Error_Runtime(sprintf('Block "%s" on template "%s" does not exist.', $name, $this->getTemplateName()), -1, $this->getTemplateName()); } diff --git a/test/Twig/Tests/Fixtures/functions/block_without_parent.test b/test/Twig/Tests/Fixtures/functions/block_without_parent.test new file mode 100644 index 0000000000..756c6b1e3a --- /dev/null +++ b/test/Twig/Tests/Fixtures/functions/block_without_parent.test @@ -0,0 +1,11 @@ +--TEST-- +"block" calling parent() with no definition in parent template +--TEMPLATE-- +{% extends "parent.twig" %} +{% block label %}{{ parent() }}{% endblock %} +--TEMPLATE(parent.twig)-- +{{ block('label') }} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Runtime: Block "label" should not call parent() in "index.twig" as the block does not exist in the parent template "parent.twig" in "index.twig" at line 3. diff --git a/test/Twig/Tests/TemplateTest.php b/test/Twig/Tests/TemplateTest.php index 74e26cd4d6..c658d18fb4 100644 --- a/test/Twig/Tests/TemplateTest.php +++ b/test/Twig/Tests/TemplateTest.php @@ -131,6 +131,17 @@ public function testDisplayBlockWithUndefinedBlock() $template->displayBlock('unknown', array()); } + /** + * @expectedException Twig_Error_Runtime + * @expectedExceptionMessage Block "foo" should not call parent() in "index.twig" as the block does not exist in the parent template "parent.twig" + */ + public function testDisplayBlockWithUndefinedParentBlock() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $template = new Twig_TemplateTest($twig, 'parent.twig'); + $template->displayBlock('foo', array(), array('foo' => array(new Twig_TemplateTest($twig, 'index.twig'), 'block_foo')), false); + } + public function testGetAttributeOnArrayWithConfusableKey() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock());