added support for traits (experimental)
authorFabien Potencier <fabien.potencier@gmail.com>
Wed, 13 Apr 2011 08:23:46 +0000 (10:23 +0200)
committerFabien Potencier <fabien.potencier@gmail.com>
Thu, 28 Apr 2011 14:22:09 +0000 (16:22 +0200)
commit221eb48ea822fbab35303ef7522653475f90b49d
tree59ad95f935af776f100ca6ea1dbd98c4c6931475
parente70cc161a33abd41969eced2c1c4f6c84ca5b36e
added support for traits (experimental)

Traits are "special" templates that define blocks that you can "include" in
other templates.

Let's take an example:

    {# 'foo' template defines the 'foo' block #}
    {% block 'foo' %}
        FOO
    {% endblock %}

    {# 'main' template defines the 'bar' block and include the 'foo' block from the 'foo' template #}
    {% extends 'base' %}

    {% use 'foo' %}

    {% block 'bar' %}
        BAR
    {% endblock %}

In the previous example, the 'main' template use the 'foo' one. It means that
the 'foo' block defined in the 'foo' template is available as if it were
defined in the 'main' template.

You can use as many 'use' statements as you want in a template:

    {% extends 'base' %}

    {% use 'foo' %}
    {% use 'bar' %}
    {% use 'foobar' %}

If two templates define the same block, the latest one wins. The template can
also overrides any block.

The 'use' tag also supports "dynamic" names:

    {% set foo = 'foo' %}

    {% use foo %}

The 'use' tag only imports a template if it does not extend another template,
if it does not define macros, and if the body is empty. But it can 'use' other
templates:

    {# 'foo' template #}
    {% block 'foo' %}
        FOO
    {% endblock %}

    {# 'bar' template #}
    {% use 'foo' %}

    {% block 'bar' %}
        BAR
    {% endblock %}

    {# 'main' template #}
    {% extends 'base' %}

    {% use 'bar' %}

In this example, the 'main' template has access to both 'foo' and 'bar'.

Traits are mainly useful when you consider blocks as reusable "functions";
like we do in Symfony2 forms or if you use Twig for code generation.
lib/Twig/Extension/Core.php
lib/Twig/Node/Module.php
lib/Twig/Node/SandboxedModule.php
lib/Twig/Parser.php
lib/Twig/Template.php
lib/Twig/TokenParser/Use.php [new file with mode: 0644]
test/Twig/Tests/Node/ModuleTest.php
test/Twig/Tests/Node/SandboxedModuleTest.php