{
public function __construct($name, $lineno)
{
- parent::__construct(array(), array('name' => $name), $lineno);
+ parent::__construct(array(), array('name' => $name, 'output' => false), $lineno);
}
public function compile(Twig_Compiler $compiler)
}
} elseif (isset($specialVars[$name])) {
$compiler->raw($specialVars[$name]);
+ } elseif ($this->getAttribute('output')) {
+ $compiler
+ ->addDebugInfo($this)
+ ->write('if (isset($context[')
+ ->string($name)
+ ->raw("])) {\n")
+ ->indent()
+ ->write('echo $context[')
+ ->string($name)
+ ->raw("];\n")
+ ->outdent()
+ ->write("}\n")
+ ;
} else {
$compiler
->raw('$this->getContext($context, ')
$node = $this->optimizeRawFilter($node, $env);
}
- $node = $this->optimizeRenderBlock($node, $env);
+ $node = $this->optimizePrintNode($node, $env);
return $node;
}
/**
- * Replaces "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()".
+ * Optimizes print nodes.
+ *
+ * It replaces:
+ *
+ * * "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()"
+ * * "echo $this->getContext('...')" with "if (isset('...')) { echo '...' }"
*
* @param Twig_NodeInterface $node A Node
* @param Twig_Environment $env The current Twig environment
*/
- protected function optimizeRenderBlock($node, $env)
+ protected function optimizePrintNode($node, $env)
{
if (!$node instanceof Twig_Node_Print) {
return $node;
}
- if ($node->getNode('expr') instanceof Twig_Node_Expression_BlockReference || $node->getNode('expr') instanceof Twig_Node_Expression_Parent) {
+ if (
+ $node->getNode('expr') instanceof Twig_Node_Expression_BlockReference ||
+ $node->getNode('expr') instanceof Twig_Node_Expression_Parent ||
+ ($node->getNode('expr') instanceof Twig_Node_Expression_Name && !$env->hasExtension('sandbox'))
+ ) {
$node->getNode('expr')->setAttribute('output', true);
return $node->getNode('expr');
$this->assertTrue($node->getAttribute('output'));
}
+ public function testRenderNameOptimizer()
+ {
+ $env = new Twig_Environment(new Twig_Loader_String(), array('cache' => false, 'autoescape' => false));
+ $env->addExtension(new Twig_Extension_Optimizer());
+ $stream = $env->parse($env->tokenize('{{ name }}', 'index'));
+
+ $node = $stream->getNode('body');
+
+ $this->assertInstanceOf('Twig_Node_Expression_Name', $node);
+ $this->assertTrue($node->getAttribute('output'));
+ }
+
/**
* @dataProvider getTestsForForOptimizer
*/