Powerful and flexible templates with Twig
Upcoming SlideShare
Loading in...5

Powerful and flexible templates with Twig






Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment
  • 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 Powerful and flexible templates with Twig Presentation Transcript

  • Powerful and flexibletemplates with TwigMichael Peacock, PHPNE December2012
  • @michaelpeacockHead Developer @groundsixAuthorOccasional conference speakermichaelpeacock.co.uktwitter.com/michaelpeacock
  • 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
  • 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,));
  • Basic usage$template = $twig->loadTemplate(mytemplate.html.twig);echo $template->render($array_of_template_variables);exit;
  • 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
  • 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
  • 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 %}
  • Extending baseExtend your base template {% include base.twig.html %}Override your blocks {% block content %} <p>This is overriding the base template</p> {% endblock %}
  • Includes{% include another_template.html.twig %}{% include template_name_in_variable %}{% include template_from_string(variable_containing_twig) %}
  • 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
  • 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}}
  • 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
  • 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’]}}
  • 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
  • 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 %}
  • Supported comparisons==!=<>>=<=
  • Ternary operators{{ logged_in ? logged_in_username : guest }}
  • Loops <ul> {% for item in array_or_iterable_object %} <li>item.getName</li> {% else %} <li>No results found</li> {% endfor %}</ul>
  • 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
  • Concatenation ~
  • 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
  • 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
  • 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/