SlideShare a Scribd company logo
1 of 38
TWIG
The flexible, fast, and secure template
language for PHP
Cesare D'Amico
cesare@wyrd.it
Cesare D'Amico
freelance php dev
Hi, nice to meet you!
cesare@wyrd.it
Twitter: __ce (double underscore)
http://cesaredami.co/
A bit of history
“So, you think PHP is a templating engine?”
Fabien Potencier - October 07, 2009
http://j.mp/lOnJU
In his opinion, php lacks:
●
concision (<?php echo $var ?>)
●
template-oriented syntax (foreach())
●
reusability
●
security + sandbox mode
A bit of history
Available solutions (October 2009):
●
Smarty3: slow
●
PHPTAL: HTML only
●
ez Components: slowest, no
inheritance
●
Dwoo: no inheritance
●
Calypso: broken (in his author's
words)
TWIG
●
Fast: Twig compiles templates to plain
optimized PHP code
●
Secure: sandbox mode for untrusted
template code
●
Flexible: powered by a flexible lexer
and parser, this allows to define
custom tags and filters
Assignments
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = ['foo': 'bar'] %}
{% set foo = 'foo' ~ 'bar' %}
{% set foo, bar = 'foo', 'bar' %}
{% set foo %}
  <div id="pagination">
    ...
  </div>
{% endset %}
Control structures – for
{% for user in users %}
{% for i in 0..10 %}
{% for l in 'a'..'z' %}
{% for l in 'a'|upper..'z'|upper %}
{% for i in 0|range(10, 2) %}
Control structures – for
loop.index
loop.index0
loop.revindex *
loop.revindex0 *
loop.first (boolean)
loop.last *  (boolean)
loop.length *
loop.parent
* Only for arrays and objects implementing
the Countable interface
Control structures – for
<ul>
  {% for user in users %}
    <li>{{ user.username|e }}</li>
  {% else %}
    <li><em>no user found</em></li>
  {% endfor %}
</ul>
Control structures – for
<ul>
  {% for id in users|keys %}
    <li>{{ id }}</li>
  {% endfor %}
</ul>
Control structures – for
<ul>
  {% for id, user in users %}
    <li>{{ id }}: {{ user.username|e }}</li>
  {% endfor %}
</ul>
Control structures – if
{% if users %}
  <ul>
    {% for user in users %}
      <li>{{ user.username|e }}</li>
    {% endfor %}
  </ul>
{% endif %}
Control structures – if/else
{% if kenny.sick %}
  Kenny is sick.
{% elseif kenny.dead %}
  You killed Kenny! You bastard!!!
{% else %}
  Kenny looks okay ­­­ so far
{% endif %}
Expressions: literals & math
"Hello World"
42 / 42.23
[foo, bar]
true / false
none
+ ­ * / %
//
**
Expressions: logic &
comparison
and or not (expression)
< > <= >= == !=
range comparisons:
{% if 1 < a < 4 %}
Even more operators!
in
.. (range)
| (apply filter)
~ (string concatenation)
. [] (attribute access: a­la object/array)
?: (ternary operator)
Filters: built-in
date: {{ post.published_at|date("m/d/Y") }}
format: “I like %s and %s”
{{ string|format(foo, "bar") }}
replace: “I like %this% and %that%”
{{ string|format(['%this%': foo, '%that%': "bar"]) }}
url_encode, json_encode, title, capitalize, upper, lower,
striptags, join, reverse, length, sort, default, keys, escape / e,
raw
Tests: built-in
divisibleby: {% if loop.index is divisibleby(3) %}
none: {{ var is none }}
even, odd
Everyone still awake?
(the best is coming...)
Inheritance – base file
<html>
<head>
{% block head %}
  <link rel="stylesheet" href="style.css" />
  <title>{% block title %}{% endblock 
%}</title>
{% endblock %}
</head>
Inheritance – base file
<body>
  <div id="content">
    {% block content %}{% endblock %}
  </div>
  <div id="footer">
    {% block footer %}
    &copy; Copyright 2010 by you.
    {% endblock %}
  </div>
</body>
</html>
Inheritance – child template
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
  {% parent %}
  <style type="text/css">
    .important { color: #336699; }
  </style>
{% endblock %}
Inheritance – child template
{% block content %}
  <h1>Index</h1>
  <p class="important">
    Welcome on my awesome homepage.
  </p>
{% endblock %}
Dynamic & conditional
inheritance
{% extends some_var %}
{% extends ajax_output ? "ajax.html"
                       : "layout.html" %}
include
{% include 'header.html' %}
...Body...
{% include 'footer.html' %}
{% include 'foo' with ['foo': 'bar'] %}
{% set vars = ['foo': 'bar'] %}
{% include 'foo' with vars %}
{% include some_var %}
{% include ajax ? 'ajax.html':'base.html' %}
Macros
{% macro input(name, value, type, size) %}
  <input type="{{ type|default('text') }}"
     name="{{ name }}" value="{{ value|e }}"
     size="{{ size|default(20) }}" />
{% endmacro %}
{% macro textarea(name, value, rows) %}
  <textarea name="{{ name }}" 
     rows="{{ rows|default(10) }}"
     cols="{{ cols|default(40) }}">
     {{ value|e }}
  </textarea>
{% endmacro %}
Macros – calling
<p>{{ _self.input('username') }}</p>
<p>{{ _self.textarea(
         'description',
         '...',
         8
      ) }}</p>
import
{% import 'forms.html' as forms %}
<dl>
  <dt>Username</dt>
  <dd>{{ forms.input('username') }}</dd>
  <dt>Password</dt>
  <dd>{{ forms.input('password', none, 
'password') }}</dd>
</dl>
<p>{{ forms.textarea('comment') }}</p>
import – hang yourself...
{% macro input(name, value, type, size) %}
  <input type="{{ type|default('text') }}"
     name="{{ name }}" value="{{ value|e }}"
     size="{{ size|default(20) }}" />
{% endmacro %}
{% import _self as forms %}
 
<p>{{ forms.input('text','username') }}</p>
i18n – needs gettext!
{% trans "Hello World!" %}
 
{% trans string_var %}
{% trans %}Hello World!{% endtrans %}
{% trans %}Hello {{ name }}!{% endtrans %}
{% trans Hello {{ name }}! %}
i18n – plurals
{% trans %}
    Hey {{ name }}, I have one apple.
{% plural apple_count %}
    Hey {{ name }}, I have {{ count }} 
apples.
{% endtrans %}
Let's use it: environment
<?php
require_once 
'/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
 
$loader = new 
Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
  'cache' => '/path/to/compilation_cache',
));
Let's use it: render
<?php
$template = $twig­>loadTemplate('tpl.html');
echo $template­>render(array(
  'the' => 'variables', 
  'go' => 'here'
));
Same as:
$template­>display(...)
Built-in loaders
$l = new Twig_Loader_Filesystem($tplDir);
$l = new Twig_Loader_Filesystem(
  array($tplDir1, $tplDir2)
);
Dummy:
$loader = new Twig_Loader_String("...");
For unit testing:
$loader = new Twig_Loader_Array($templates);
Built-in extensions
Core (automatically registered)
Escaper
Sandbox
I18n
You can create your own extensions if you need so:
- implement interface Twig_ExtensionInterface
- extend Twig_Extension so you need only implement
needed methods
$twig­>addExtension(
  new Twig_Extension_Escaper()
);
Thanks everyone!
?
12-14 Maggio 2011
http://www.phpday.it/
Please, rate this talk!
Feel like bashing?
Urge saying you fell in love
with this presentation?
Now you can!
http://joind.in/2151

More Related Content

What's hot

Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3
Fabien Potencier
 

What's hot (19)

Making Sense of Twig
Making Sense of TwigMaking Sense of Twig
Making Sense of Twig
 
Codeware
CodewareCodeware
Codeware
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
PHP 5.4 New Features
PHP 5.4 New FeaturesPHP 5.4 New Features
PHP 5.4 New Features
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
New in php 7
New in php 7New in php 7
New in php 7
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changed
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 

Viewers also liked

Clat 2011 preparation tips presented by paradygm law
Clat 2011 preparation tips presented by paradygm lawClat 2011 preparation tips presented by paradygm law
Clat 2011 preparation tips presented by paradygm law
guestb13d83
 
Series 14 a contents of email
Series 14 a  contents of emailSeries 14 a  contents of email
Series 14 a contents of email
Satpanth Dharm
 
My strategicplan.strategyhuddle.052610
My strategicplan.strategyhuddle.052610My strategicplan.strategyhuddle.052610
My strategicplan.strategyhuddle.052610
M3Planning
 
Corporate+Health+Coach+Introduction
Corporate+Health+Coach+IntroductionCorporate+Health+Coach+Introduction
Corporate+Health+Coach+Introduction
jacquim7
 

Viewers also liked (20)

WordPress-Templates mit Twig erstellen - PHPUGFFM
WordPress-Templates mit Twig erstellen - PHPUGFFMWordPress-Templates mit Twig erstellen - PHPUGFFM
WordPress-Templates mit Twig erstellen - PHPUGFFM
 
Writing Headlines infographic
Writing Headlines infographicWriting Headlines infographic
Writing Headlines infographic
 
Clat 2011 preparation tips presented by paradygm law
Clat 2011 preparation tips presented by paradygm lawClat 2011 preparation tips presented by paradygm law
Clat 2011 preparation tips presented by paradygm law
 
Series 14 a contents of email
Series 14 a  contents of emailSeries 14 a  contents of email
Series 14 a contents of email
 
Y:\Thinking
Y:\ThinkingY:\Thinking
Y:\Thinking
 
Series 43 Gazetteer of bombay presidency -vol IX -part II -year 1899
Series 43  Gazetteer of bombay presidency -vol IX -part II -year 1899Series 43  Gazetteer of bombay presidency -vol IX -part II -year 1899
Series 43 Gazetteer of bombay presidency -vol IX -part II -year 1899
 
My strategicplan.strategyhuddle.052610
My strategicplan.strategyhuddle.052610My strategicplan.strategyhuddle.052610
My strategicplan.strategyhuddle.052610
 
Japanese Culture
Japanese CultureJapanese Culture
Japanese Culture
 
Ciclo Básico de Procesamiento de Datos
Ciclo Básico de Procesamiento de DatosCiclo Básico de Procesamiento de Datos
Ciclo Básico de Procesamiento de Datos
 
801-ADMONUMB
801-ADMONUMB801-ADMONUMB
801-ADMONUMB
 
Corporate+Health+Coach+Introduction
Corporate+Health+Coach+IntroductionCorporate+Health+Coach+Introduction
Corporate+Health+Coach+Introduction
 
Diana
DianaDiana
Diana
 
My Experience to Be Studentpreneur
My Experience to Be StudentpreneurMy Experience to Be Studentpreneur
My Experience to Be Studentpreneur
 
GE 2 minutes book 06 & 07-jun-1951 -suggesting our abkkp samaj is formed by ...
GE 2  minutes book 06 & 07-jun-1951 -suggesting our abkkp samaj is formed by ...GE 2  minutes book 06 & 07-jun-1951 -suggesting our abkkp samaj is formed by ...
GE 2 minutes book 06 & 07-jun-1951 -suggesting our abkkp samaj is formed by ...
 
R edes inte
R edes inteR edes inte
R edes inte
 
Settings
SettingsSettings
Settings
 
Oe3 attachment -chhama maafi
Oe3  attachment -chhama maafiOe3  attachment -chhama maafi
Oe3 attachment -chhama maafi
 
GE 11 history of sanatan dharm in abkkps
GE 11  history of sanatan dharm in abkkpsGE 11  history of sanatan dharm in abkkps
GE 11 history of sanatan dharm in abkkps
 
It's All About Context
It's All About ContextIt's All About Context
It's All About Context
 
Plan UMC
Plan UMCPlan UMC
Plan UMC
 

Similar to TWIG: the flexible, fast and secure template language for PHP

Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHP
Lee Boynton
 
PHP from the point of view of a webhoster
PHP from the point of view of a webhosterPHP from the point of view of a webhoster
PHP from the point of view of a webhoster
Dominic Lüchinger
 
Federico Feroldi: PHP in Yahoo!
Federico Feroldi: PHP in Yahoo!Federico Feroldi: PHP in Yahoo!
Federico Feroldi: PHP in Yahoo!
Francesco Fullone
 
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1
ADARSH BHATT
 

Similar to TWIG: the flexible, fast and secure template language for PHP (20)

(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems
 
Zephir - How to create PHP extension
Zephir - How to create PHP extensionZephir - How to create PHP extension
Zephir - How to create PHP extension
 
Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHP
 
Desktop Apps with PHP and Titanium
Desktop Apps with PHP and TitaniumDesktop Apps with PHP and Titanium
Desktop Apps with PHP and Titanium
 
PHP tutorial | ptutorial
PHP tutorial | ptutorialPHP tutorial | ptutorial
PHP tutorial | ptutorial
 
Php through the eyes of a hoster: PHPNW10
Php through the eyes of a hoster: PHPNW10Php through the eyes of a hoster: PHPNW10
Php through the eyes of a hoster: PHPNW10
 
PHP from the point of view of a webhoster
PHP from the point of view of a webhosterPHP from the point of view of a webhoster
PHP from the point of view of a webhoster
 
Html5 Open Video Tutorial
Html5 Open Video TutorialHtml5 Open Video Tutorial
Html5 Open Video Tutorial
 
Php intro
Php introPhp intro
Php intro
 
Modern PHP
Modern PHPModern PHP
Modern PHP
 
JS Days HTML5 Flash and the Battle for Faster Cat Videos
JS Days HTML5 Flash and the Battle for Faster Cat VideosJS Days HTML5 Flash and the Battle for Faster Cat Videos
JS Days HTML5 Flash and the Battle for Faster Cat Videos
 
Federico Feroldi: PHP in Yahoo!
Federico Feroldi: PHP in Yahoo!Federico Feroldi: PHP in Yahoo!
Federico Feroldi: PHP in Yahoo!
 
Federico Feroldi Php In Yahoo
Federico Feroldi Php In YahooFederico Feroldi Php In Yahoo
Federico Feroldi Php In Yahoo
 
Scaling with Symfony - PHP UK
Scaling with Symfony - PHP UKScaling with Symfony - PHP UK
Scaling with Symfony - PHP UK
 
Возможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OSВозможности интерпретатора Python в NX-OS
Возможности интерпретатора Python в NX-OS
 
Interoperable PHP
Interoperable PHPInteroperable PHP
Interoperable PHP
 
GDD HTML5, Flash, and the Battle for Faster Cat Videos
GDD HTML5, Flash, and the Battle for Faster Cat VideosGDD HTML5, Flash, and the Battle for Faster Cat Videos
GDD HTML5, Flash, and the Battle for Faster Cat Videos
 
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1
 
Phalcon Framework: San Antonio Web Developers Group
Phalcon Framework: San Antonio Web Developers Group Phalcon Framework: San Antonio Web Developers Group
Phalcon Framework: San Antonio Web Developers Group
 
Php
PhpPhp
Php
 

Recently uploaded

Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
FIDO Alliance
 

Recently uploaded (20)

Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 

TWIG: the flexible, fast and secure template language for PHP