fabpot/Twig — Issue #477: Consider using local/instance variables instead of context
Author: schmittjoh
Created: 2011-10-20 13:12:25+00:00
State: open

While working on [twig.js](http://github.com/schmittjoh/twig.js), I've found that Twig often sets variables on the context which it could set as local variables instead without cluttering the context. As example, see the for-loop implementation above for PHP code, below for Javascript code where I made some modifications.

```php
$context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
```

```javascript
// line 1
context['_parent'] = context;
var seq = twig.range(1, 5);
var loop = {
'index0': 0,
'index': 1,
'first': true
};
if (twig.countable(seq)) {
var length = twig.count(seq);
loop['revindex0'] = length - 1;
loop['revindex'] = length;
loop['length'] = length;
loop['last'] = 1 === length;
}
```

Another example, is how macros work. I think an instance variable could be used for these:

```php
env->loadTemplate("macros.twig");
// ...
echo twig_escape_filter($this->env, $this->getAttribute($context["__internal_9162a8dce4458f34ee79ba42a570ec4d_1"], "link", array("/login", "Please login.", "Login", ), "method"), "html", null, true);
```

The benefit of using local variables is that you wouldn't have to do a clean-up when leaving the scope (e.g. as done in the for loop), but it would be done by PHP automatically. The instance variables for macros would avoid round trips through the environment, and also lead to smaller code size (not so important for PHP, but very important for Javascript). Also, the round-trip through $this->getAttribute() could be avoided by introducing a new node for macro calls.