21.10.2015 Views

1-33

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Symfony2 – Franz Jordán 2011<br />

<br />

<br />

<br />

Twig defines two types of special syntax:<br />

{{ ... }}: "Says something": prints a variable or the result of an expression to the<br />

template;<br />

{% ... %}: "Does something": a tag that controls the logic of the template; it is used to<br />

execute statements such as for-loops for example.<br />

There is a third syntax used for creating comments: {# this is a comment #}. This syntax<br />

can be used across multiple lines like the PHP-equivalent /* comment*/ syntax.<br />

Twig also contains filters, which modify content before being rendered. The following makes the<br />

title variable all uppercase before rendering it:<br />

{{ title | upper }}<br />

Twig comes with a long list of tags and filters that are available by default. You can even add<br />

your own extensions to Twig as needed.<br />

Registering a Twig extension is as easy as creating a new service and tagging it<br />

withtwig.extension tag.<br />

As you'll see throughout the documentation, Twig also supports functions and new functions can<br />

be easily added. For example, the following uses a standard for tag and the cycle function to<br />

print ten div tags, with alternating odd, even classes:<br />

{% for i in 0..10 %}<br />

<br />

<br />

<br />

{% endfor %}<br />

Throughout this chapter, template examples will be shown in both Twig and PHP.<br />

Why Twig?<br />

Twig templates are meant to be simple and won't process PHP tags. This is by design: the Twig<br />

template system is meant to express presentation, not program logic. The more you use Twig,<br />

the more you'll appreciate and benefit from this distinction. And of course, you'll be loved by<br />

web designers everywhere.<br />

Twig can also do things that PHP can't, such as true template inheritance (Twig templates<br />

compile down to PHP classes that inherit from each other), whitespace control, sandboxing, and<br />

the inclusion of custom functions and filters that only affect templates. Twig contains little<br />

features that make writing templates easier and more concise. Take the following example,<br />

which combines a loop with a logical if statement:<br />

<br />

{% for user in users %}<br />

{{ user.username }}<br />

{% else %}<br />

No users found<br />

{% endfor %}<br />

<br />

69

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!