Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

Powerful and flexible templates with Twig

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Wird geladen in …3
×

Hier ansehen

1 von 24 Anzeige
Anzeige

Weitere Verwandte Inhalte

Diashows für Sie (20)

Ähnlich wie Powerful and flexible templates with Twig (20)

Anzeige

Weitere von Michael Peacock (20)

Aktuellste (20)

Anzeige

Powerful and flexible templates with Twig

  1. 1. Powerful and flexible templates with Twig Michael Peacock, PHPNE December 2012
  2. 2. @michaelpeacock Head Developer @groundsix Author Occasional conference speaker michaelpeacock.co.uk twitter.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 variables Associative array Keys are used to access the data in the templates Values are displayed / rendered in the templates Values can be: Arrays Objects Data
  7. 7. Base templates A base template defines “blocks” which can be overridden by other templates The block can contain default content; overriding is optional Makes it easy to change small amounts of a base 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 isn't overriden by another template</p> {% endblock %}
  9. 9. Extending base Extend 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 variables Output 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 types You can also instruct twig to call a method on an object or access a property of an array as opposed to relying on the dynamic magic {{object.method()}} {{array[‘variable’]}}
  15. 15. Setting variables You can also create variables on-the-fly {% set new_variable = ‘variable’ %} Useful when working with objects or arrays, as you can pull out data, manipulate it and use it as a 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 data Iteration 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. Twig Powerful, flexible templates Easy to build and extend Syntax thats friendly for designers Allows some level of control in the templates A bit of a double edged sword - with great template flexibility comes great responsibility! http://twig.sensiolabs.org/

Hinweis der Redaktion

  • 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

×