SlideShare a Scribd company logo
TWIG
Tips & Tricks
STRUCTURE
AND
INTERNAL
REPRESENTATION
Twig's three tags
Twig parses just three simple tags:
{# comment tag - aren't rendered and they are also
multi-line
#} – do nothing!
{{ 'print tag' }}
– say something!
{% set this = 'block tag' %}
- do something!
Twig Brief, Tips&Tricks
Twig Brief, Tips&Tricks
The Lexer
The lexer tokenizes a template source code into a token stream. The default
lexer recognizes 13 different token types.
Here is the output for the Hello {{ name }} template:
TEXT_TYPE(Hello )
VAR_START_TYPE()
NAME_TYPE(name)
VAR_END_TYPE()
EOF_TYPE()
The Parser
The parser converts the token stream into an AST (Abstract Syntax Tree), or
a node tree. The core extension defines the basic nodes like: for, if, ... and the
expression nodes.
Here is the output for the Hello {{ name }} template:
Twig_Node_Module(
Twig_Node_Text(Hello )
Twig_Node_Print(
Twig_Node_Expression_Name(name)
)
)
Templates’ sources
app/cache/prod/templates.php :
<?php return array (
'::base.html.twig' => '<project_path>/app/Resources/views/base.html.twig',
'::header.html.twig' => '<project_path>/app/Resources/views/header.html.twig',
'::footer.html.twig' => '<project_path>/app/Resources/views/footer.html.twig',
'CrfMainBundle:Homepage:homepage.html.twig' =>
'<project_path>/src/Crf/MainBundle/Resources/views/Homepage/homepage.
html.twig',
…
);
The Compiler
The last step is done by the compiler. It takes a node tree as an input and
generates PHP code usable for runtime execution of the template.
The generated template for a Hello {{ name }} template reads as follows:
/* Hello {{ name }} */
class __TwigTemplate_1121b6f109fe93ebe8c6e22e3712bceb extends Twig_Template
{
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "Hello ";
echo twig_escape_filter($this->env, $this->getContext($context, "name"), "html", null,
true);
}
// some more code
}
Twig Brief, Tips&Tricks
Twig Brief, Tips&Tricks
FUNCTIONALITIES
AND
USAGE
FOR Loops
{% for user in users %}
{{user.name}}
{% else %}
{{ ‘No users’ }}
{% endfor %}
{% for i in 0..10 %}
{% for l in 'a'..'z' %}
{% for l in 'a'|upper..'z'|upper %}
{% for i in 0|range(10, 2) %}
{% for blog in blogs %}
<div class="link {{ cycle(['even', 'odd'], loop.index0) }}">
{{ blog.description }}
</div>
{% endfor %}
IF Tag
Multiple branches:
{% if kenny.sick %}
Kenny is sick.
{% elseif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
Ternary operator:
{{ human.alive ? ‘It’s alive’ : ‘Wasted’ }}
- define a macro in a separate twig file:
- include your reusable macro where you want:
MACROS - a reusable and configurable
snippet of HTML
XSS protection - escaping
Spaceless
Use the spaceless tag to remove whitespace between HTML tags, not
whitespace within HTML tags or whitespace in plain text:
{% spaceless %}
<div>
<strong>foo bar</strong>
</div>
{% endspaceless %}
{# output will be <div><strong>foo bar</strong></div> #}
{% set value = 'no spaces' %}
<li> {{- value }} </li>
{# outputs '<li>no spaces </li>' #}
Verbatim
The verbatim tag marks sections as being raw text that should not be parsed.
For example to put Twig syntax as example into a template you can use this
snippet:
{% verbatim %}
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endverbatim %}
You can also use this tag to avoid the conflict with the default angular.js syntax,
if you do not want to change it.
The i18n extension
To use it, first, install the Extensions library.
You need to register this extension before using the trans block, then configure
the gettext extension:
// Set language to French
putenv('LC_ALL=fr_FR');
setlocale(LC_ALL, 'fr_FR');
// Specify the location of the translation tables
bindtextdomain('myAppPhp', 'includes/locale');
bind_textdomain_codeset('myAppPhp', 'UTF-8');
// Choose domain
textdomain('myAppPhp');
{% trans "Hello World!" %}
{% trans string_variable %}
{% trans %}
Hello {{ name }}
{% endtrans %}
EXTENDING
AND
CUSTOMIZING
Setting your own custom syntax
You may want to use simultaneously the default syntax of
angular( {{ }} ) with twig - what to do?
Change the twig default syntax to your preferred one!
Creating a TWIG extension
Twig is very customizable, and allows you to create custom tools, like tags,
filters, operators, functions by extending the core(libtwigExtensionCore.php) .
The principle of creating an extension is the same for any element you
wish to customize: you create a class which extends the Twig_Extension
abstract class, then overwrite the desired function, and inject your service or
create a custom function which you intend to use in the templates.
use it in your templates:
{{ entityHelper.attributeByStore(promo, attribute) }}
Sandbox
• It’s a regular Twig extension, {% sandbox %}
• Disabled by default.
• It allows to restrict the functions, filters, tags and object properties used in the
templates.
• It’s based on security policies.
$loader = new Twig_Loader_Filesystem('...');
$twig = new Twig_Environment($loader, array());
$properties = array(‘User’ => array('name', 'address'));
$policy = new Twig_Sandbox_SecurityPolicy(
array(), array(), array(), $properties, array()
);
$sandbox = new Twig_Extension_Sandbox(
$policy, true // all templates are sandboxed
);
$twig->addExtension($sandbox);
The template now displays an error:
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
{{ user.name }} - ok
{{ user.address }} - ok
{{ user.age }} - is not accessible
Whoops, looks like something went wrong.
User: {{ user.age }}
Calling "age" property on a "User" object is not allowed …
Security policy arguments:
$policy = new Twig_Sandbox_SecurityPolicy(
$tags,
$filters,
$methods,
$properties,
$functions
);
Allow just 3 filters:
$policy = new Twig_Sandbox_SecurityPolicy(
$tags,
array('escape', 'upper', 'lower'),
$methods,
$properties,
$functions
);
{{ include }} vs {% include %}
1) If you want to store contents of a file in a variable if you want to repeat it twice:
{% set content = include('test.twig') %}
Instead of:
{% set content %}
{% include 'test.twig' %}
{% endset %}
2) If you want to add filters:
{{ include('alert.twig') | upper }}
Its tag equivalent:
{% set temp %}
{% include 'alert.twig' %}
{% endset %}
{{ temp | upper }}
Also, according to the documentation, it looks recommended to use {{ include() }} to
fit with best practices.
Conditional layouts
{% extends request.ajax ? "base_ajax.html" : "base.html" %}
{% block content %}
This is the content to be displayed.
{% endblock %}
Dynamic inclusion of a template:
{% include var|default('index') ~ '_foo.html' %}
Accessing an object attribute
{{ user.name }}
name can be:
* an item on an array
* property on an object
* getName()
{{ user[‘name’] }}
or you can force it to *just* fetch “name” as an array
item
Convert format and format date
Defensive design
Use a default value when possible:
{{ variable|default("value") }}
Ignore missing templates:
{% include 'section_' ~ slug ~ '.twig' ignore missing %}
Define fallback templates
{% extends ['layout_' ~ locale ~ '.html.twig', 'layout.html.twig'] %}
Render a Template without a custom
Controller
acme_privacy:
path: /privacy
defaults:
_controller: FrameworkBundle:Template:template
template: static/privacy.html.twig
maxAge: 86400
sharedAge: 86400
{{ render(url('acme_privacy')) }}
Thank you very much for your
attendance!
Useful links:
http://twig.sensiolabs.org/
http://symfony.com/doc/current/components/templating/index.html
http://symfony.com/doc/current/cookbook/templating/index.html
http://fabien.potencier.org/article/34/templating-engines-in-php
http://www.slideshare.net/fabpot/twig-the-flexible-fast-and-securetemplate-
language-for-php
http://www.slideshare.net/cesaredamico/webtech-twig
http://www.slideshare.net/weaverryan/being-dangerous-with-twig
http://www.slideshare.net/javier.eguiluz/twig-tips-and-tricks
Ad

More Related Content

What's hot (20)

Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
Rafael Dohms
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2
markstory
 
Making Sense of Twig
Making Sense of TwigMaking Sense of Twig
Making Sense of Twig
Brandon Kelly
 
Twig Templating
Twig TemplatingTwig Templating
Twig Templating
Rj Bautista
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
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
Cesare D'Amico
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
mattbuzz
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
Vineet Kumar Saini
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
CiaranMcNulty
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
Kumar
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
baabtra.com - No. 1 supplier of quality freshers
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
Tarek Mahmud Apu
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
Damian T. Gordon
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
Jorn Oomen
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
Rafael Dohms
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2
markstory
 
Making Sense of Twig
Making Sense of TwigMaking Sense of Twig
Making Sense of Twig
Brandon Kelly
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
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
Cesare D'Amico
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
mattbuzz
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
CiaranMcNulty
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
Kumar
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
Jorn Oomen
 

Similar to Twig Brief, Tips&Tricks (20)

Powerful and flexible templates with Twig
Powerful and flexible templates with Twig Powerful and flexible templates with Twig
Powerful and flexible templates with Twig
Michael Peacock
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
Maurizio Pelizzone
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012
Rene Bakx
 
Python (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationPython (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network Automation
Rick Sherman
 
learnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxlearnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptx
bestboybulshaawi
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
Ted Kulp
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.ppt
Patiento Del Mar
 
Java 17
Java 17Java 17
Java 17
Mutlu Okuducu
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 
Struts 2
Struts 2Struts 2
Struts 2
Lalit Garg
 
backend
backendbackend
backend
tutorialsruby
 
backend
backendbackend
backend
tutorialsruby
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
Nitay Neeman
 
Idoc script beginner guide
Idoc script beginner guide Idoc script beginner guide
Idoc script beginner guide
Vinay Kumar
 
Into The Box 2018 - CBT
Into The Box 2018 - CBTInto The Box 2018 - CBT
Into The Box 2018 - CBT
Ortus Solutions, Corp
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
ARORACOCKERY2111
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
Salesforce Developers
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
Roberto Suggi Liverani
 
Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals   maksym moskvychevTwig internals - Maksym MoskvychevTwig internals   maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
DrupalCampDN
 
Powerful and flexible templates with Twig
Powerful and flexible templates with Twig Powerful and flexible templates with Twig
Powerful and flexible templates with Twig
Michael Peacock
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
Maurizio Pelizzone
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012
Rene Bakx
 
Python (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationPython (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network Automation
Rick Sherman
 
learnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxlearnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptx
bestboybulshaawi
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
Ted Kulp
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.ppt
Patiento Del Mar
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
Nitay Neeman
 
Idoc script beginner guide
Idoc script beginner guide Idoc script beginner guide
Idoc script beginner guide
Vinay Kumar
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
ARORACOCKERY2111
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
Salesforce Developers
 
Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals   maksym moskvychevTwig internals - Maksym MoskvychevTwig internals   maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
DrupalCampDN
 
Ad

Recently uploaded (20)

Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Ad

Twig Brief, Tips&Tricks

  • 3. Twig's three tags Twig parses just three simple tags: {# comment tag - aren't rendered and they are also multi-line #} – do nothing! {{ 'print tag' }} – say something! {% set this = 'block tag' %} - do something!
  • 6. The Lexer The lexer tokenizes a template source code into a token stream. The default lexer recognizes 13 different token types. Here is the output for the Hello {{ name }} template: TEXT_TYPE(Hello ) VAR_START_TYPE() NAME_TYPE(name) VAR_END_TYPE() EOF_TYPE()
  • 7. The Parser The parser converts the token stream into an AST (Abstract Syntax Tree), or a node tree. The core extension defines the basic nodes like: for, if, ... and the expression nodes. Here is the output for the Hello {{ name }} template: Twig_Node_Module( Twig_Node_Text(Hello ) Twig_Node_Print( Twig_Node_Expression_Name(name) ) )
  • 8. Templates’ sources app/cache/prod/templates.php : <?php return array ( '::base.html.twig' => '<project_path>/app/Resources/views/base.html.twig', '::header.html.twig' => '<project_path>/app/Resources/views/header.html.twig', '::footer.html.twig' => '<project_path>/app/Resources/views/footer.html.twig', 'CrfMainBundle:Homepage:homepage.html.twig' => '<project_path>/src/Crf/MainBundle/Resources/views/Homepage/homepage. html.twig', … );
  • 9. The Compiler The last step is done by the compiler. It takes a node tree as an input and generates PHP code usable for runtime execution of the template. The generated template for a Hello {{ name }} template reads as follows: /* Hello {{ name }} */ class __TwigTemplate_1121b6f109fe93ebe8c6e22e3712bceb extends Twig_Template { protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "Hello "; echo twig_escape_filter($this->env, $this->getContext($context, "name"), "html", null, true); } // some more code }
  • 13. FOR Loops {% for user in users %} {{user.name}} {% else %} {{ ‘No users’ }} {% endfor %} {% for i in 0..10 %} {% for l in 'a'..'z' %} {% for l in 'a'|upper..'z'|upper %} {% for i in 0|range(10, 2) %} {% for blog in blogs %} <div class="link {{ cycle(['even', 'odd'], loop.index0) }}"> {{ blog.description }} </div> {% endfor %}
  • 14. IF Tag Multiple branches: {% if kenny.sick %} Kenny is sick. {% elseif kenny.dead %} You killed Kenny! You bastard!!! {% else %} Kenny looks okay --- so far {% endif %} Ternary operator: {{ human.alive ? ‘It’s alive’ : ‘Wasted’ }}
  • 15. - define a macro in a separate twig file: - include your reusable macro where you want: MACROS - a reusable and configurable snippet of HTML
  • 16. XSS protection - escaping
  • 17. Spaceless Use the spaceless tag to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text: {% spaceless %} <div> <strong>foo bar</strong> </div> {% endspaceless %} {# output will be <div><strong>foo bar</strong></div> #} {% set value = 'no spaces' %} <li> {{- value }} </li> {# outputs '<li>no spaces </li>' #}
  • 18. Verbatim The verbatim tag marks sections as being raw text that should not be parsed. For example to put Twig syntax as example into a template you can use this snippet: {% verbatim %} <ul> {% for item in seq %} <li>{{ item }}</li> {% endfor %} </ul> {% endverbatim %} You can also use this tag to avoid the conflict with the default angular.js syntax, if you do not want to change it.
  • 19. The i18n extension To use it, first, install the Extensions library. You need to register this extension before using the trans block, then configure the gettext extension: // Set language to French putenv('LC_ALL=fr_FR'); setlocale(LC_ALL, 'fr_FR'); // Specify the location of the translation tables bindtextdomain('myAppPhp', 'includes/locale'); bind_textdomain_codeset('myAppPhp', 'UTF-8'); // Choose domain textdomain('myAppPhp'); {% trans "Hello World!" %} {% trans string_variable %} {% trans %} Hello {{ name }} {% endtrans %}
  • 21. Setting your own custom syntax You may want to use simultaneously the default syntax of angular( {{ }} ) with twig - what to do? Change the twig default syntax to your preferred one!
  • 22. Creating a TWIG extension Twig is very customizable, and allows you to create custom tools, like tags, filters, operators, functions by extending the core(libtwigExtensionCore.php) . The principle of creating an extension is the same for any element you wish to customize: you create a class which extends the Twig_Extension abstract class, then overwrite the desired function, and inject your service or create a custom function which you intend to use in the templates.
  • 23. use it in your templates: {{ entityHelper.attributeByStore(promo, attribute) }}
  • 24. Sandbox • It’s a regular Twig extension, {% sandbox %} • Disabled by default. • It allows to restrict the functions, filters, tags and object properties used in the templates. • It’s based on security policies. $loader = new Twig_Loader_Filesystem('...'); $twig = new Twig_Environment($loader, array()); $properties = array(‘User’ => array('name', 'address')); $policy = new Twig_Sandbox_SecurityPolicy( array(), array(), array(), $properties, array() ); $sandbox = new Twig_Extension_Sandbox( $policy, true // all templates are sandboxed ); $twig->addExtension($sandbox);
  • 25. The template now displays an error: {% sandbox %} {% include 'user.html' %} {% endsandbox %} {{ user.name }} - ok {{ user.address }} - ok {{ user.age }} - is not accessible Whoops, looks like something went wrong. User: {{ user.age }} Calling "age" property on a "User" object is not allowed …
  • 26. Security policy arguments: $policy = new Twig_Sandbox_SecurityPolicy( $tags, $filters, $methods, $properties, $functions ); Allow just 3 filters: $policy = new Twig_Sandbox_SecurityPolicy( $tags, array('escape', 'upper', 'lower'), $methods, $properties, $functions );
  • 27. {{ include }} vs {% include %} 1) If you want to store contents of a file in a variable if you want to repeat it twice: {% set content = include('test.twig') %} Instead of: {% set content %} {% include 'test.twig' %} {% endset %} 2) If you want to add filters: {{ include('alert.twig') | upper }} Its tag equivalent: {% set temp %} {% include 'alert.twig' %} {% endset %} {{ temp | upper }} Also, according to the documentation, it looks recommended to use {{ include() }} to fit with best practices.
  • 28. Conditional layouts {% extends request.ajax ? "base_ajax.html" : "base.html" %} {% block content %} This is the content to be displayed. {% endblock %} Dynamic inclusion of a template: {% include var|default('index') ~ '_foo.html' %}
  • 29. Accessing an object attribute {{ user.name }} name can be: * an item on an array * property on an object * getName() {{ user[‘name’] }} or you can force it to *just* fetch “name” as an array item
  • 30. Convert format and format date
  • 31. Defensive design Use a default value when possible: {{ variable|default("value") }} Ignore missing templates: {% include 'section_' ~ slug ~ '.twig' ignore missing %} Define fallback templates {% extends ['layout_' ~ locale ~ '.html.twig', 'layout.html.twig'] %}
  • 32. Render a Template without a custom Controller acme_privacy: path: /privacy defaults: _controller: FrameworkBundle:Template:template template: static/privacy.html.twig maxAge: 86400 sharedAge: 86400 {{ render(url('acme_privacy')) }}
  • 33. Thank you very much for your attendance!