SlideShare a Scribd company logo
Powerful and flexible
templates with Twig
Michael Peacock, PHPNE December
2012
@michaelpeacock

Head Developer @groundsix
Author
Occasional conference speaker
michaelpeacock.co.uk
twitter.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 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
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
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 %}
Extending base


Extend 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 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}}
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 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’]}}
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
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 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
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
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/

More Related Content

PPT
Dance for the puppet master: G6 Tech Talk
KEY
Phpne august-2012-symfony-components-friends
PDF
Phinx talk
KEY
CodeIgniter 3.0
KEY
PyCon US 2012 - State of WSGI 2
PDF
What happens in laravel 4 bootstraping
KEY
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PPT
Real time server
Dance for the puppet master: G6 Tech Talk
Phpne august-2012-symfony-components-friends
Phinx talk
CodeIgniter 3.0
PyCon US 2012 - State of WSGI 2
What happens in laravel 4 bootstraping
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
Real time server

What's hot (20)

PDF
Getting to The Loop - London Wordpress Meetup July 28th
PDF
用Tornado开发RESTful API运用
PDF
Flask - Backend com Python - Semcomp 18
PDF
Codeigniter : Two Step View - Concept Implementation
PDF
Hacking ansible
PDF
Why Task Queues - ComoRichWeb
PDF
More tips n tricks
PDF
Databases and MySQL
PPTX
Flask – Python
ODT
PDF
Ansible leveraging 2.0
PDF
Introducing Assetic: Asset Management for PHP 5.3
PDF
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
PDF
PuppetCamp Ghent - What Not to Do with Puppet
PDF
Filling the flask
PDF
Puppet: What _not_ to do
PDF
Puppet at janrain
PDF
Javascript Frameworks for Joomla
PDF
Getting Started with Ansible
PDF
Codeigniter : Using Third Party Components - Zend Framework Components
Getting to The Loop - London Wordpress Meetup July 28th
用Tornado开发RESTful API运用
Flask - Backend com Python - Semcomp 18
Codeigniter : Two Step View - Concept Implementation
Hacking ansible
Why Task Queues - ComoRichWeb
More tips n tricks
Databases and MySQL
Flask – Python
Ansible leveraging 2.0
Introducing Assetic: Asset Management for PHP 5.3
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
PuppetCamp Ghent - What Not to Do with Puppet
Filling the flask
Puppet: What _not_ to do
Puppet at janrain
Javascript Frameworks for Joomla
Getting Started with Ansible
Codeigniter : Using Third Party Components - Zend Framework Components
Ad

Similar to Powerful and flexible templates with Twig (20)

PDF
Twig Brief, Tips&Tricks
PDF
Django Rest Framework and React and Redux, Oh My!
KEY
Twig for Drupal @ Frontendunited Amsterdam 2012
PDF
Into The Box 2018 - CBT
PDF
Introduction to Spring MVC
KEY
Geek Moot '09 -- Smarty 101
PPTX
Asp.net mvc training
PDF
Drupal 8: Theming
PDF
Tornadoweb
PDF
Twig, the flexible, fast, and secure template language for PHP
PPTX
Use Symfony2 components inside WordPress
PDF
Django Class-based views (Slovenian)
ODP
Bring the fun back to java
KEY
PHPConf-TW 2012 # Twig
PPTX
Asp.NET MVC
PDF
Django design-patterns
PPTX
AngularJs-training
PPT
Create a web-app with Cgi Appplication
PPTX
Basics of Java Script (JS)
PPTX
Struts 2
Twig Brief, Tips&Tricks
Django Rest Framework and React and Redux, Oh My!
Twig for Drupal @ Frontendunited Amsterdam 2012
Into The Box 2018 - CBT
Introduction to Spring MVC
Geek Moot '09 -- Smarty 101
Asp.net mvc training
Drupal 8: Theming
Tornadoweb
Twig, the flexible, fast, and secure template language for PHP
Use Symfony2 components inside WordPress
Django Class-based views (Slovenian)
Bring the fun back to java
PHPConf-TW 2012 # Twig
Asp.NET MVC
Django design-patterns
AngularJs-training
Create a web-app with Cgi Appplication
Basics of Java Script (JS)
Struts 2
Ad

More from Michael Peacock (20)

PPTX
Immutable Infrastructure with Packer Ansible and Terraform
PPTX
Test driven APIs with Laravel
PPTX
Symfony Workflow Component - Introductory Lightning Talk
PPTX
Alexa, lets make a skill
PPTX
API Development with Laravel
PPTX
An introduction to Laravel Passport
PDF
Refactoring to symfony components
PPT
Introduction to OOP with PHP
KEY
KEY
Evolution of a big data project
PPTX
Real time voice call integration - Confoo 2012
PPTX
Dealing with Continuous Data Processing, ConFoo 2012
PPTX
Data at Scale - Michael Peacock, Cloud Connect 2012
PPTX
Supermondays twilio
PPTX
PHP & Twilio
PPTX
PHP Continuous Data Processing
PPTX
PHP North East Registry Pattern
PPTX
PHP North East - Registry Design Pattern
PPTX
Supermondays: Jenkins CI lightning talk
PPTX
Corporate Structures - September 2010
Immutable Infrastructure with Packer Ansible and Terraform
Test driven APIs with Laravel
Symfony Workflow Component - Introductory Lightning Talk
Alexa, lets make a skill
API Development with Laravel
An introduction to Laravel Passport
Refactoring to symfony components
Introduction to OOP with PHP
Evolution of a big data project
Real time voice call integration - Confoo 2012
Dealing with Continuous Data Processing, ConFoo 2012
Data at Scale - Michael Peacock, Cloud Connect 2012
Supermondays twilio
PHP & Twilio
PHP Continuous Data Processing
PHP North East Registry Pattern
PHP North East - Registry Design Pattern
Supermondays: Jenkins CI lightning talk
Corporate Structures - September 2010

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Big Data Technologies - Introduction.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Electronic commerce courselecture one. Pdf
PPT
Teaching material agriculture food technology
PDF
cuic standard and advanced reporting.pdf
PPTX
Cloud computing and distributed systems.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
A Presentation on Artificial Intelligence
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Machine learning based COVID-19 study performance prediction
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Advanced methodologies resolving dimensionality complications for autism neur...
“AI and Expert System Decision Support & Business Intelligence Systems”
Big Data Technologies - Introduction.pptx
MYSQL Presentation for SQL database connectivity
Encapsulation_ Review paper, used for researhc scholars
Electronic commerce courselecture one. Pdf
Teaching material agriculture food technology
cuic standard and advanced reporting.pdf
Cloud computing and distributed systems.
The Rise and Fall of 3GPP – Time for a Sabbatical?
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
A Presentation on Artificial Intelligence
20250228 LYD VKU AI Blended-Learning.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Machine learning based COVID-19 study performance prediction
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Dropbox Q2 2025 Financial Results & Investor Presentation
Diabetes mellitus diagnosis method based random forest with bat algorithm

Powerful and flexible templates with Twig

  • 1. Powerful and flexible templates with Twig Michael Peacock, PHPNE December 2012
  • 2. @michaelpeacock Head Developer @groundsix Author Occasional conference speaker michaelpeacock.co.uk twitter.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 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. 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. 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. 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. 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 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. 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 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. 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. 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 %}
  • 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 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
  • 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. 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/

Editor's Notes

  • #5: 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
  • #6: Load the template into twig, then render by passing an array of variables