SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 itRafael Dohms
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2markstory
 
Making Sense of Twig
Making Sense of TwigMaking Sense of Twig
Making Sense of TwigBrandon 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 & ArraysHenry 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 PHPCesare D'Amico
 
PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5Jason Austin
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
 
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 TutorialLorna 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 26SynapseindiaComplaints
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 

Was ist angesagt? (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
 

Ähnlich wie 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 2012Rene Bakx
 
Python (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationPython (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationRick Sherman
 
learnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxlearnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxbestboybulshaawi
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Ted Kulp
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptPatiento Del Mar
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay 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.pdfARORACOCKERY2111
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_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 ClientsSalesforce 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 moskvychevDrupalCampDN
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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...Jeffrey Haguewood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
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 SavingEdi Saputra
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 

Kürzlich hochgeladen (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 

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!