Powerful and flexible templates with Twig


Published on

Published in: Technology
1 Comment
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

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
  • Powerful and flexible templates with Twig

    1. 1. Powerful and flexibletemplates with TwigMichael Peacock, PHPNE December2012
    2. 2. @michaelpeacockHead Developer @groundsixAuthorOccasional conference speakermichaelpeacock.co.uktwitter.com/michaelpeacock
    3. 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. 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. 5. Basic usage$template = $twig->loadTemplate(mytemplate.html.twig);echo $template->render($array_of_template_variables);exit;
    6. 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. 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. 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. 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. 10. Includes{% include another_template.html.twig %}{% include template_name_in_variable %}{% include template_from_string(variable_containing_twig) %}
    11. 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. 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. 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. 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. 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. 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. 17. Supported comparisons==!=<>>=<=
    18. 18. Ternary operators{{ logged_in ? logged_in_username : guest }}
    19. 19. Loops <ul> {% for item in array_or_iterable_object %} <li>item.getName</li> {% else %} <li>No results found</li> {% endfor %}</ul>
    20. 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. 21. Concatenation ~
    22. 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. 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. 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/
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.