Powerful and flexible templates with Twig

Uploaded on


More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide
  • There are other loader types too; loading from string, or load from an array (keys are template names, values are templates as strings) You can create your own too, if you implement the Twig_LoaderInterface
  • Load the template into twig, then render by passing an array of variables


  • 1. Powerful and flexibletemplates with TwigMichael Peacock, PHPNE December2012
  • 2. @michaelpeacockHead Developer @groundsixAuthorOccasional conference speakermichaelpeacock.co.uktwitter.com/michaelpeacock
  • 3. Installation Create a composer.json file { "require": { "twig/twig": "1.*" } } Download composer curl -s http://getcomposer.org/installer | php Run composer to install twig php composer.phar install
  • 4. Setup$loader = new Twig_Loader_Filesystem(__DIR__ . /templates/);// ideally sits in a dependency injection container$twig = new Twig_Environment($loader, array(cache => __DIR__ . /cache/templates,));
  • 5. Basic usage$template = $twig->loadTemplate(mytemplate.html.twig);echo $template->render($array_of_template_variables);exit;
  • 6. Template variablesAssociative array Keys are used to access the data in the templates Values are displayed / rendered in the templatesValues can be: Arrays Objects Data
  • 7. Base templatesA base template defines “blocks” which can beoverridden by other templatesThe block can contain default content;overriding is optionalMakes it easy to change small amounts of abase template on only a few specific pages
  • 8. Blocks {% block content %} {% endblock %} {% block content %} <p>This is some default content which will be displayed if the template is used directly or if it isnt overriden by another template</p> {% endblock %}
  • 9. Extending baseExtend your base template {% include base.twig.html %}Override your blocks {% block content %} <p>This is overriding the base template</p> {% endblock %}
  • 10. Includes{% include another_template.html.twig %}{% include template_name_in_variable %}{% include template_from_string(variable_containing_twig) %}
  • 11. A note on context By default all included templates and base templates inherit their template variables from the template you are rendering You can change this by passing a list of variables when including a template{% include another_template.html.twig with other_variables only %} You can also pass more variables by omitting the only keyword
  • 12. Printing variablesOutput is automatically escaped {{my_variable}}But you can tell twig to not escape some data(using a filter, which we will look at shortly) {{my_variable|raw}}
  • 13. Dynamic Magic{{ check if }} is an array and bar a valid element; foo.bar foo if not, and if foo is an object, check that bar is a valid property; if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead); if not, and if foo is an object, check that getBar is a valid method; if not, and if foo is an object, check that isBar is a valid method; if not, return a null value. Source: http://twig.sensiolabs.org/doc/templates.html#variables
  • 14. Explicit typesYou can also instruct twig to call a method onan object or access a property of an array asopposed to relying on the dynamic magic{{object.method()}}{{array[‘variable’]}}
  • 15. Setting variablesYou can also create variables on-the-fly{% set new_variable = ‘variable’ %}Useful when working with objects or arrays, asyou can pull out data, manipulate it and use it asa variable in its own right
  • 16. Conditions{% if logged_in_user is not null %}<p>Welcome logged_in_user.name. <a href="/logout">Logout</a></p>{% else %}<p><a href="/login">Login</a></p>{% endif %}
  • 17. Supported comparisons==!=<>>=<=
  • 18. Ternary operators{{ logged_in ? logged_in_username : guest }}
  • 19. Loops <ul> {% for item in array_or_iterable_object %} <li>item.getName</li> {% else %} <li>No results found</li> {% endfor %}</ul>
  • 20. Loop dataIteration of a loop (1 indexed) {{loop.index}}Parent loop iteration (1 indexed) {{loop.parent.loop.index}}Other information loop.index0 (0 indexed iteration) loop.revindex (reversed index) loop.first (true if first iteration) loop.last (truue if last iteration) loop.length
  • 21. Concatenation ~
  • 22. Filters Many of them are twig wrappers for PHP functions Date: {{ article.publication_date|date("d/m/Y") }} Number format {{500123.0123|number_format}} Url encode {{variable|url_encode()}} Length (of string or items in array) {{variable| length}} You can use multiple filters e.g. {{var|trans|raw}} Lots more! http://twig.sensiolabs.org/doc/filters/index.html
  • 23. Custom filters Create a function First parameter is what appears before the filter, other parameters are set when you use the filter if required (ideally, these should be optional)function twig_filter_gravatar($email, $default=mm, $size=30){return "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" .urlencode($default) . "&s=" . $size;} Add the filter $twig->addFilter(gravatar, new Twig_Filter_Function(twig_filter_gravatar)); Use the filter {{user.getEmail|gravatar}} Unfortunately closures can’t be used yet
  • 24. TwigPowerful, flexible templatesEasy to build and extendSyntax thats friendly for designersAllows some level of control in the templatesA bit of a double edged sword - with greattemplate flexibility comes great responsibility! http://twig.sensiolabs.org/