SlideShare una empresa de Scribd logo
1 de 24
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/

Más contenido relacionado

La actualidad más candente

Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28thChris Adams
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用Felinx Lee
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Lar21
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationAbdul Malik Ikhsan
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansiblebcoca
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
More tips n tricks
More tips n tricksMore tips n tricks
More tips n tricksbcoca
 
Databases and MySQL
Databases and MySQLDatabases and MySQL
Databases and MySQLThings Lab
 
Ansible leveraging 2.0
Ansible leveraging 2.0Ansible leveraging 2.0
Ansible leveraging 2.0bcoca
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Kris Wallsmith
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesDjangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 MinutesNina Zakharenko
 
PuppetCamp Ghent - What Not to Do with Puppet
PuppetCamp Ghent - What Not to Do with PuppetPuppetCamp Ghent - What Not to Do with Puppet
PuppetCamp Ghent - What Not to Do with PuppetWalter Heck
 
Filling the flask
Filling the flaskFilling the flask
Filling the flaskJason Myers
 
Puppet: What _not_ to do
Puppet: What _not_ to doPuppet: What _not_ to do
Puppet: What _not_ to doPuppet
 
Puppet at janrain
Puppet at janrainPuppet at janrain
Puppet at janrainPuppet
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Getting Started with Ansible
Getting Started with AnsibleGetting Started with Ansible
Getting Started with Ansibleahamilton55
 
Codeigniter : Using Third Party Components - Zend Framework Components
Codeigniter : Using Third Party Components - Zend Framework ComponentsCodeigniter : Using Third Party Components - Zend Framework Components
Codeigniter : Using Third Party Components - Zend Framework ComponentsAbdul Malik Ikhsan
 

La actualidad más candente (20)

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

Similar a Powerful and flexible templates with Twig

Twig Brief, Tips&Tricks
Twig Brief, Tips&TricksTwig Brief, Tips&Tricks
Twig Brief, Tips&TricksAndrei Burian
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Rene Bakx
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptPatiento Del Mar
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Ted Kulp
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc trainingicubesystem
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Themingdrubb
 
Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPTwig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPFabien Potencier
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Maurizio Pelizzone
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigWake Liu
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplicationolegmmiller
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)Ajay Khatri
 

Similar a Powerful and flexible templates with Twig (20)

Twig Brief, Tips&Tricks
Twig Brief, Tips&TricksTwig Brief, Tips&Tricks
Twig Brief, Tips&Tricks
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012
 
Into The Box 2018 - CBT
Into The Box 2018 - CBTInto The Box 2018 - CBT
Into The Box 2018 - CBT
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.ppt
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Theming
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Twig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHPTwig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHP
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 

Más de Michael Peacock

Immutable Infrastructure with Packer Ansible and Terraform
Immutable Infrastructure with Packer Ansible and TerraformImmutable Infrastructure with Packer Ansible and Terraform
Immutable Infrastructure with Packer Ansible and TerraformMichael Peacock
 
Test driven APIs with Laravel
Test driven APIs with LaravelTest driven APIs with Laravel
Test driven APIs with LaravelMichael Peacock
 
Symfony Workflow Component - Introductory Lightning Talk
Symfony Workflow Component - Introductory Lightning TalkSymfony Workflow Component - Introductory Lightning Talk
Symfony Workflow Component - Introductory Lightning TalkMichael Peacock
 
Alexa, lets make a skill
Alexa, lets make a skillAlexa, lets make a skill
Alexa, lets make a skillMichael Peacock
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with LaravelMichael Peacock
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel PassportMichael Peacock
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony componentsMichael Peacock
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Evolution of a big data project
Evolution of a big data projectEvolution of a big data project
Evolution of a big data projectMichael Peacock
 
Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012Michael Peacock
 
Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012Michael Peacock
 
Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012Michael Peacock
 
PHP Continuous Data Processing
PHP Continuous Data ProcessingPHP Continuous Data Processing
PHP Continuous Data ProcessingMichael Peacock
 
PHP North East Registry Pattern
PHP North East Registry PatternPHP North East Registry Pattern
PHP North East Registry PatternMichael Peacock
 
PHP North East - Registry Design Pattern
PHP North East - Registry Design PatternPHP North East - Registry Design Pattern
PHP North East - Registry Design PatternMichael Peacock
 
Supermondays: Jenkins CI lightning talk
Supermondays: Jenkins CI lightning talkSupermondays: Jenkins CI lightning talk
Supermondays: Jenkins CI lightning talkMichael Peacock
 
Corporate Structures - September 2010
Corporate Structures - September 2010Corporate Structures - September 2010
Corporate Structures - September 2010Michael Peacock
 

Más de Michael Peacock (20)

Immutable Infrastructure with Packer Ansible and Terraform
Immutable Infrastructure with Packer Ansible and TerraformImmutable Infrastructure with Packer Ansible and Terraform
Immutable Infrastructure with Packer Ansible and Terraform
 
Test driven APIs with Laravel
Test driven APIs with LaravelTest driven APIs with Laravel
Test driven APIs with Laravel
 
Symfony Workflow Component - Introductory Lightning Talk
Symfony Workflow Component - Introductory Lightning TalkSymfony Workflow Component - Introductory Lightning Talk
Symfony Workflow Component - Introductory Lightning Talk
 
Alexa, lets make a skill
Alexa, lets make a skillAlexa, lets make a skill
Alexa, lets make a skill
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with Laravel
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony components
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Vagrant
VagrantVagrant
Vagrant
 
Evolution of a big data project
Evolution of a big data projectEvolution of a big data project
Evolution of a big data project
 
Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012
 
Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012
 
Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012
 
Supermondays twilio
Supermondays twilioSupermondays twilio
Supermondays twilio
 
PHP & Twilio
PHP & TwilioPHP & Twilio
PHP & Twilio
 
PHP Continuous Data Processing
PHP Continuous Data ProcessingPHP Continuous Data Processing
PHP Continuous Data Processing
 
PHP North East Registry Pattern
PHP North East Registry PatternPHP North East Registry Pattern
PHP North East Registry Pattern
 
PHP North East - Registry Design Pattern
PHP North East - Registry Design PatternPHP North East - Registry Design Pattern
PHP North East - Registry Design Pattern
 
Supermondays: Jenkins CI lightning talk
Supermondays: Jenkins CI lightning talkSupermondays: Jenkins CI lightning talk
Supermondays: Jenkins CI lightning talk
 
Corporate Structures - September 2010
Corporate Structures - September 2010Corporate Structures - September 2010
Corporate Structures - September 2010
 

Último

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

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/

Notas del editor

  1. 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
  2. Load the template into twig, then render by passing an array of variables