added support for an array of templates to the include tag

This commit is contained in:
Fabien Potencier
2011-08-27 13:37:56 +02:00
parent acd3663062
commit 35a8a0d155
6 changed files with 48 additions and 12 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.2.0
* added support for an array of templates to the "include" tag ({% include ['foo', 'bar'] %})
* added support for bitwise operators in expressions
* added the "attribute" function to allow getting dynamic attributes on variables
* added Twig_Loader_Chain
+8
View File
@@ -877,6 +877,14 @@ directly::
$twig->loadTemplate('template.twig')->display(array('template' => $template));
.. versionadded:: 1.2
The possibility to pass an array of templates has been added in Twig 1.2.
You can also provide a list of templates that are checked for existence before
inclusion. The first template that exists will be included::
{% include ['page_detailed.html', 'page.html'] %}
Import
~~~~~~
+24
View File
@@ -316,6 +316,30 @@ class Twig_Environment
return $this->loadedTemplates[$cls] = new $cls($this);
}
public function resolveTemplate($names)
{
if (!is_array($names)) {
$names = array($names);
}
foreach ($names as $name) {
if ($name instanceof Twig_Template) {
return $name;
}
try {
return $this->loadTemplate($name);
} catch (Exception $e) {
}
}
if (1 === count($names)) {
throw $e;
}
throw new Twig_Error_Loader(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
}
/**
* Clears the internal template cache.
*/
+2 -8
View File
@@ -40,15 +40,9 @@ class Twig_Node_Include extends Twig_Node implements Twig_NodeOutputInterface
;
} else {
$compiler
->write("\$template = ")
->write("\$template = \$this->env->resolveTemplate(")
->subcompile($this->getNode('expr'))
->raw(";\n")
->write("if (!\$template")
->raw(" instanceof Twig_Template) {\n")
->indent()
->write("\$template = \$this->env->loadTemplate(\$template);\n")
->outdent()
->write("}\n")
->raw(");\n")
->write('$template->display(')
;
}
@@ -0,0 +1,12 @@
--TEST--
"include" tag
--TEMPLATE--
{% include ["foo.twig", "bar.twig"] %}
{% include ["bar.twig", "foo.twig"] %}
--TEMPLATE(foo.twig)--
foo
--DATA--
return array()
--EXPECT--
foo
foo
+1 -4
View File
@@ -56,10 +56,7 @@ class Twig_Tests_Node_IncludeTest extends Twig_Tests_Node_TestCase
);
$node = new Twig_Node_Include($expr, null, false, 0);
$tests[] = array($node, <<<EOF
\$template = ((true) ? ("foo") : ("foo"));
if (!\$template instanceof Twig_Template) {
\$template = \$this->env->loadTemplate(\$template);
}
\$template = \$this->env->resolveTemplate(((true) ? ("foo") : ("foo")));
\$template->display(\$context);
EOF
);