``Twig_Function``::
$twig = new Twig_Environment($loader);
- $twig->addGlobal('lipsum', new Twig_Function(new Text(), 'getLipsum'));
+ $twig->addGlobal('fn_lipsum', new Twig_Function(new Text(), 'getLipsum'));
// or
$twig->addGlobal('text', new Text());
- $twig->addGlobal('lipsum', new Twig_Function('text', 'getLipsum'));
+ $twig->addGlobal('fn_lipsum', new Twig_Function('text', 'getLipsum'));
+
+To avoid name clashes with variables, function names must be prefixed with
+``fn_`` when defined (the prefix must not be added in templates).
The first argument to ``Twig_Function`` is an object or a variable name
referencing an object.
.. code-block:: jinja
+ {# A lipsum variable does not override the lipsum function #}
+ {% set lipsum = 'foo' %}
+
{{ lipsum(40) }}
.. note::
public function compile($compiler)
{
+ // functions must be prefixed with fn_
+ $this->getNode('name')->setAttribute('name', 'fn_'.$this->getNode('name')->getAttribute('name'));
+
$compiler
->raw('$this->callFunction($context, ')
->subcompile($this->getNode('name'))
foreach ($this->getAttribute('imports') as $name => $alias) {
$compiler
->write('$context[')
- ->repr($alias)
+ ->repr('fn_'.$alias)
->raw('] = new Twig_Function(')
->subcompile($this->getNode('var'))
->raw(', ')
--DATA--
return array(
'foo' => new Foo(),
- 'lower' => new Twig_Function('foo', 'strToLower'),
- 'lower1' => new Twig_Function(new Foo(), 'strToLower'))
+ 'fn_lower' => new Twig_Function('foo', 'strToLower'),
+ 'fn_lower1' => new Twig_Function(new Foo(), 'strToLower'))
--EXPECT--
foo
foo
{{ foo() }}
--DATA--
-$twig->addGlobal('foo', new Twig_Function(new Foo(), 'getFoo'));
-$twig->addGlobal('bar', new Twig_Function('barObj', 'getFoo'));
+$twig->addGlobal('fn_foo', new Twig_Function(new Foo(), 'getFoo'));
+$twig->addGlobal('fn_bar', new Twig_Function('barObj', 'getFoo'));
return array('barObj' => new Foo());
--EXPECT--
foo