The first release candidate for Twig 1.12.0 has just been released. This
version introduces a lot of nice enhancements that should simplify the way
developers and web designers work with Twig.
Extending Twig the easy Way
You can extend Twig by creating an extension or by calling method directly on
the Twig environment. Let’s see how you can create a new function.
Until now, it was a bit cumbersome and quite limited; you were able to map a
Twig function to a PHP function or to a method from a Twig extension class
(and depending on which you choose, you need to use a specific class):
$twig->addFunction('some_function', new Twig_Function_Function('some_function'));
$twig->addFunction('some_function', new Twig_Function_Method($extension, 'someMethod'));
As of 1.12, you can use any valid PHP callable, and everything is managed by
one class:
$twig->addFunction(new Twig_SimpleFunction('some_function', 'some_function'));
$twig->addFunction(new Twig_SimpleFunction('some_function', array($extension, 'someMethod')));
$twig->addFunction(new Twig_SimpleFunction('some_function', function () { /* ... */ }));
Calling Things the flexible Way
When defining a macro, you can now set default values for all arguments
instead of relying on the default filter:
{# before #}
{% macro input(name, value, type, size) %}
<input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|default('')|e }}" size="{{ size|20 }}" />
{% endmacro %}
{# after #}
{% macro input(name, value = "", type = "text", size = 20) %}
<input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" />
{% endmacro %}
Some functions and filters in Twig have a long list of arguments and
remembering their order and their meaning is not easy. You can now use named
arguments to make things easier and more explicit:
{# before #}
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
{# after #}
{{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
A new include
function has been introduced to simplify the including of other files when
passing multiple options:
{# before #}
{% sandbox %}
{% include 'page.html' ignore missing %}
{% endsandbox %}
{# after #}
{{ include('page.html', sandboxed = true, ignore_missing = true) }}
The ternary operator syntax has been extended to simplify some common use
cases:
{# standard syntax #}
{{ foo ? 'yes' : 'no' }}
{# extended syntaxes as of Twig 1.12 #}
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
As always, everything should be backward compatible, meaning that all your
existing templates will still work as before. Of course, if that’s not the
case, report it as soon as possible so that we can fix the regressions before
the 1.12.0 final is released later this week.