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!
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
}
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

More Related Content

What's hot

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
 
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
 
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 arraysKumar
 
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 OOPWildan 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
 
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
 

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
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2
 
Making Sense of Twig
Making Sense of TwigMaking Sense of Twig
Making Sense of Twig
 
Twig Templating
Twig TemplatingTwig Templating
Twig Templating
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
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
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
 
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
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
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
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 

Similar to Twig Brief, Tips&Tricks

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 ApplicationsAlessandro Molina
 
Struts 2
Struts 2Struts 2
Struts 2
Lalit Garg
 
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
 

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
 
Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012
 
Python (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationPython (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network Automation
 
learnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxlearnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptx
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.ppt
 
Java 17
Java 17Java 17
Java 17
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Struts 2
Struts 2Struts 2
Struts 2
 
backend
backendbackend
backend
 
backend
backendbackend
backend
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Idoc script beginner guide
Idoc script beginner guide Idoc script beginner guide
Idoc script beginner guide
 
Into The Box 2018 - CBT
Into The Box 2018 - CBTInto The Box 2018 - CBT
Into The Box 2018 - CBT
 
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
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
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
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
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
 

Recently uploaded

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

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!
  • 4.
  • 5.
  • 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 }
  • 10.
  • 11.
  • 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!