21.10.2015 Views

1-33

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Symfony2 – Franz Jordán 2011<br />

Twig Template Caching<br />

Twig is fast. Each Twig template is compiled down to a native PHP class that is rendered at<br />

runtime. The compiled classes are located in the app/cache/{environment}/twig directory<br />

(where{environment} is the environment, such as dev or prod) and in some cases can be<br />

useful while debugging. See Environments for more information on environments.<br />

When debug mode is enabled (common in the dev environment), a Twig template will be<br />

automatically recompiled when changes are made to it. This means that during development you<br />

can happily make changes to a Twig template and instantly see the changes without needing to<br />

worry about clearing any cache.<br />

When debug mode is disabled (common in the prod environment), however, you must clear the<br />

Twig cache directory so that the Twig templates will regenerate. Remember to do this when<br />

deploying your application.<br />

Template Inheritance and Layouts<br />

More often than not, templates in a project share common elements, like the header, footer,<br />

sidebar or more. In Symfony2, we like to think about this problem differently: a template can be<br />

decorated by another one. This works exactly the same as PHP classes: template inheritance<br />

allows you to build a base "layout" template that contains all the common elements of your site<br />

defined as blocks (think "PHP class with base methods"). A child template can extend the base<br />

layout and override any of its blocks (think "PHP subclass that overrides certain methods of its<br />

parent class").<br />

First, build a base layout file:<br />

{# app/Resources/views/base.html.twig #}<br />

<br />

<br />

<br />

<br />

{% block title %}Test Application{% endblock %}<br />

<br />

<br />

<br />

{% block sidebar %}<br />

<br />

Home<br />

Blog<br />

<br />

{% endblock %}<br />

<br />

<br />

{% block body %}{% endblock %}<br />

<br />

<br />

<br />

70

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

Saved successfully!

Ooh no, something went wrong!