SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
Twig internals
About speaker
What is Twig?
Maintenance page of Bartik theme.
Drupal 7, PHP template
Drupal 8, Twig template
Why we are here?
To remember (or learn) the basics of Twig
Recall Twig main features and advantages
Find out extending possibilities
Debug Twig core a little bit
Print data
{{ foo }}
Twig start points
Do something
{% for %}
Basic syntax
strings
numbers
objects
arrays
null
true
false
hashes
{% for value in
Traversable %}
{% else %}
{% endfor %}
{% ifexpression %}
{% elseif %}
{% endif %}
{% else %}
-> .
~.
Data types Operators
Control
Structures
Functions
Tests
Filters
From Functions to
Filters and Tests
Functions in Twig works the same as
in PHP – they apply arguments in
parentheses and return result.
Filters are modifying the
value by some rules.
Value Filter Params
Tests are checking
the value by test rule.
Value Test Paramsis
Test sign
Filter sign
Extending templates
Layout
block header
block footer
Blocksidebar
block content
Module template
Blocksidebar
extends
Your template
block content
Block definitions in child
templates replace its content
in parent template
You have to define only
that blocks that you
want to overwrite
You can overwrite
any block from
parent template
extends
Replaces per block
Re-usage of templates
Your template
Parent
template
Layout
Parent
template
{% extends … %}
Replaces per block
Block
definitions
{% use … %}
Peace of
template
{% include … %}
Macro
(Peace of template
with arguments)
{% import … %}
{% embed … %}
Creating Twig extension
class MyExtension extends Twig_Extension
{
public function getFilters()
{
return array(
new Twig_SimpleFilter(„my_filter', „callback'),
);
}
}
$twig->addExtension(new MyExtension());
Custom extension allows to define:
•Globals
•Functions
•Filters
•Tags
•Tests
•Operators
Extending Twig for Jedi
Make a
service
global for
twig
Create a macro
when need to
reuse template
with parameters
Forgot to calculate some
stuff before rendering
template?
- Go to the dark side,
make your service global
Want to define some logic
in declarative way?
- Do not restrain your
emotions, make a macro
For strong minds the only
way is to write custom
tag, in custom bundle and
publish it on GitHub
Twig
Extension
Also you could create a
Twig extension to define
your functions, filters,
tests and operators. And
share the extension
between projects
Custom
tag
How it works?
Data from
controller
Lexer
Parser
Compiler
Caching
system
Web page
Hello word!
index.html.twig Evaluate
Lexer splits input
text into language
primitives in one
stream
Parser builds node tree
according to nesting rules
(Abstract Syntax Tree)
Compiler generates
PHP code based on
Abstract syntax Tree
Each template is
represented as a PHP class
in the caching system
First time Twig has to
parse input file and
build cache entry
Lexer
1 Hello.
2 {{.name|capitalize.}}
3
For example there is a file index.html.twig
Lexer understands language primitives and
outputs them in one stream
Lexer
Hm.. There is some text.
TEXT_TYPE(“Hello n”)
Hm.. Seems this is start of tag
VAR_START_TYPE()
TEXT_TYPE(“Hello n”),
VAR_START_TYPE(),
NAME_TYPE(“name”),
OPERATOR_TYPE(“|”),
NAME_TYPE(“capitalize”),
VAR_END_TYPE(),
EOF_TYPE()
Now I see a variable
NAME_TYPE(“name”)
Hm.. Some operator
OPERATOR_TYPE(“|”)
Wow! Again some name
NAME_TYPE(“capitalize”)
Parser
Parser
TEXT_TYPE(“Hello n”),
VAR_START_TYPE(),
NAME_TYPE(“name”),
OPERATOR_TYPE(“|”),
NAME_TYPE(“capitalize”),
VAR_END_TYPE(),
EOF_TYPE()
Template: index.html.twig
Text: “Hello n”
Echo result of calculation
Filter: capitalize
Value of variable “name”
The goal of parser is to find dependencies between elements. It understands that
one thing can contain others. At the end if builds the whole document in object-
oriented way when one objects consist of other.
Compiler
Template: index.html.twig
Text: “Hello n”
Echo result of calculation
Filter: capitalize
Value of variable
“name”
Compiler is a tool that converts Abstract Syntax Tree into a PHP code. For each
type of node compiler has own handlers. Each handler knows how to transform
node of AST into raw PHP string. So, at the output we have PHP code in one
stream.
Compiler
echo “Hello n”;
echo ucfirst($name);
This code will be put
into PHP representation
of index.html.twig
The power of customization
Lexer
Goals Solutions
As a PHP lover
I want to support <?: ?> tags
so that it makes me happy
As an idealist
I need {% single %} case in “for” tag
So that it controls case when there
is only one element in input data
As a “hot fixer”
I want to have {% log %} tag
so that I can save data
between tags into log file
Parser
Compiler
Create a node class that
implements Twig_NodeInterface.
Define custom logic in compile()
method. You also need to create
custom TokenParser to initialize
new node class.
Create a Token Parser class that
implements
Twig_TokenParserInterface.
Define you logic in parse()
method. Use existing compilers
for all cases.
Change default Twig lexer with
custom one that extends from
core and understands new tags
as {{ and }}
Sandbox – include untrusted templates
Secure template
include
Users can edit templates online ?
They can do something
you wouldn’t like
Let’s filter
user’s input by
white-list rules!
In sandboxed template you can use
only allowed:
•Methods of your classes,
•Properties of your classes
•Filters
•Tags
Find your reason to love Twig
Twig is a modern template engine for PHP
Fast: Twig compiles templates down to plain optimized PHP
code. The overhead compared to regular PHP code was reduced to
the very minimum.
Secure: Twig has a sandbox mode to evaluate untrusted
template code. This allows Twig to be used as a template language
for applications where users may modify the template design.
Flexible: Twig is powered by a flexible lexer and parser. This
allows the developer to define its own custom tags and filters, and
create its own DSL.
Thank you
My contacts:
Skype name: maxim_432
Email: maksym.moskvychev@gmail.com

Weitere ähnliche Inhalte

Was ist angesagt?

python file handling
python file handlingpython file handling
python file handlingjhona2z
 
web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VI PPT  by Bhavsingh Malothweb programming Unit VI PPT  by Bhavsingh Maloth
web programming Unit VI PPT by Bhavsingh MalothBhavsingh Maloth
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
What's with the 1s and 0s? Making sense of binary data at scale with Tika and...
What's with the 1s and 0s? Making sense of binary data at scale with Tika and...What's with the 1s and 0s? Making sense of binary data at scale with Tika and...
What's with the 1s and 0s? Making sense of binary data at scale with Tika and...gagravarr
 
Tutorial 5 (lucene)
Tutorial 5 (lucene)Tutorial 5 (lucene)
Tutorial 5 (lucene)Kira
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Full Text Search with Lucene
Full Text Search with LuceneFull Text Search with Lucene
Full Text Search with LuceneWO Community
 
32sql server
32sql server32sql server
32sql serverSireesh K
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glanceKnoldus Inc.
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloadingomkar bhagat
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Nitin Aggarwal
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experiencedzynofustechnology
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3Duong Thanh
 

Was ist angesagt? (20)

python file handling
python file handlingpython file handling
python file handling
 
30csharp
30csharp30csharp
30csharp
 
web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VI PPT  by Bhavsingh Malothweb programming Unit VI PPT  by Bhavsingh Maloth
web programming Unit VI PPT by Bhavsingh Maloth
 
Java best practices
Java best practicesJava best practices
Java best practices
 
What's with the 1s and 0s? Making sense of binary data at scale with Tika and...
What's with the 1s and 0s? Making sense of binary data at scale with Tika and...What's with the 1s and 0s? Making sense of binary data at scale with Tika and...
What's with the 1s and 0s? Making sense of binary data at scale with Tika and...
 
Tutorial 5 (lucene)
Tutorial 5 (lucene)Tutorial 5 (lucene)
Tutorial 5 (lucene)
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Full Text Search with Lucene
Full Text Search with LuceneFull Text Search with Lucene
Full Text Search with Lucene
 
32sql server
32sql server32sql server
32sql server
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
Filehandling
FilehandlingFilehandling
Filehandling
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3
 

Ähnlich wie Twig internals - Maksym MoskvychevTwig internals maksym moskvychev

Being Dangerous with Twig
Being Dangerous with TwigBeing Dangerous with Twig
Being Dangerous with TwigRyan Weaver
 
Code Generation using T4
Code Generation using T4Code Generation using T4
Code Generation using T4Joubin Najmaie
 
CustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputsCustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputsSuite Solutions
 
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)Ryan Weaver
 
T3dallas typoscript
T3dallas typoscriptT3dallas typoscript
T3dallas typoscriptzdavis
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Rene Bakx
 
Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content TransformationAlfresco Software
 
Backend Development - Django
Backend Development - DjangoBackend Development - Django
Backend Development - DjangoAhmad Sakhleh
 
Latex workshop: Essentials and Practices
Latex workshop: Essentials and PracticesLatex workshop: Essentials and Practices
Latex workshop: Essentials and PracticesMohamed Alrshah
 
Html & CSS - Best practices 2-hour-workshop
Html & CSS - Best practices 2-hour-workshopHtml & CSS - Best practices 2-hour-workshop
Html & CSS - Best practices 2-hour-workshopVero Rebagliatte
 
.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12aminmesbahi
 

Ähnlich wie Twig internals - Maksym MoskvychevTwig internals maksym moskvychev (20)

Being Dangerous with Twig
Being Dangerous with TwigBeing Dangerous with Twig
Being Dangerous with Twig
 
Code Generation using T4
Code Generation using T4Code Generation using T4
Code Generation using T4
 
CustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputsCustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputs
 
Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)Being Dangerous with Twig (Symfony Live Paris)
Being Dangerous with Twig (Symfony Live Paris)
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
T3dallas typoscript
T3dallas typoscriptT3dallas typoscript
T3dallas typoscript
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012
 
Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content Transformation
 
Backend Development - Django
Backend Development - DjangoBackend Development - Django
Backend Development - Django
 
Latex workshop: Essentials and Practices
Latex workshop: Essentials and PracticesLatex workshop: Essentials and Practices
Latex workshop: Essentials and Practices
 
Java basics
Java basicsJava basics
Java basics
 
Html & CSS - Best practices 2-hour-workshop
Html & CSS - Best practices 2-hour-workshopHtml & CSS - Best practices 2-hour-workshop
Html & CSS - Best practices 2-hour-workshop
 
Html5 tutorial
Html5 tutorialHtml5 tutorial
Html5 tutorial
 
Html5 - Tutorial
Html5 - TutorialHtml5 - Tutorial
Html5 - Tutorial
 
.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12
 
T4 presentation
T4 presentationT4 presentation
T4 presentation
 

Mehr von DrupalCampDN

Drupal - Changing the Web by Connecting Open Minds - Josef Dabernig
Drupal - Changing the Web by Connecting Open Minds - Josef DabernigDrupal - Changing the Web by Connecting Open Minds - Josef Dabernig
Drupal - Changing the Web by Connecting Open Minds - Josef DabernigDrupalCampDN
 
Dependency Injection in Drupal 8 - Стадник АндрейQweqwe
Dependency Injection in Drupal 8 - Стадник АндрейQweqweDependency Injection in Drupal 8 - Стадник АндрейQweqwe
Dependency Injection in Drupal 8 - Стадник АндрейQweqweDrupalCampDN
 
Our AWS Cloud Journey - Andrew Boag
Our AWS Cloud Journey - Andrew BoagOur AWS Cloud Journey - Andrew Boag
Our AWS Cloud Journey - Andrew BoagDrupalCampDN
 
Guzzle in Drupal 8 and as a REST client - Артем Мирошник
Guzzle in Drupal 8 and as a REST client - Артем МирошникGuzzle in Drupal 8 and as a REST client - Артем Мирошник
Guzzle in Drupal 8 and as a REST client - Артем МирошникDrupalCampDN
 
Blocks & Layouts in D7 - Josef Dabernig
Blocks & Layouts in D7 - Josef DabernigBlocks & Layouts in D7 - Josef Dabernig
Blocks & Layouts in D7 - Josef DabernigDrupalCampDN
 
CKEditor в Drupal: тонкая настройка и кастомизация - Osman Seferov
CKEditor в Drupal: тонкая настройка и кастомизация - Osman SeferovCKEditor в Drupal: тонкая настройка и кастомизация - Osman Seferov
CKEditor в Drupal: тонкая настройка и кастомизация - Osman SeferovDrupalCampDN
 
Drush - use full power - Alexander Schedrov
Drush - use full power - Alexander SchedrovDrush - use full power - Alexander Schedrov
Drush - use full power - Alexander SchedrovDrupalCampDN
 
Это Drupal, %username%! - Андрей Черноус
Это Drupal, %username%! - Андрей ЧерноусЭто Drupal, %username%! - Андрей Черноус
Это Drupal, %username%! - Андрей ЧерноусDrupalCampDN
 
Migrate - new way site upgrade
Migrate - new way site upgradeMigrate - new way site upgrade
Migrate - new way site upgradeDrupalCampDN
 
Caching on highload Drupal site - Alexander Shumenko
Caching on highload Drupal site - Alexander ShumenkoCaching on highload Drupal site - Alexander Shumenko
Caching on highload Drupal site - Alexander ShumenkoDrupalCampDN
 
Rich Text in Drupal - Вадим Валуев
Rich Text in Drupal - Вадим ВалуевRich Text in Drupal - Вадим Валуев
Rich Text in Drupal - Вадим ВалуевDrupalCampDN
 
May the parallelity be with you! Distributed computing using Erlang language ...
May the parallelity be with you! Distributed computing using Erlang language ...May the parallelity be with you! Distributed computing using Erlang language ...
May the parallelity be with you! Distributed computing using Erlang language ...DrupalCampDN
 
Panels как философия - Alexander Danilenko
Panels как философия - Alexander DanilenkoPanels как философия - Alexander Danilenko
Panels как философия - Alexander DanilenkoDrupalCampDN
 
DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...DrupalCampDN
 
Презентация модуля YandexMoney - Yury Glushkov
Презентация модуля YandexMoney - Yury GlushkovПрезентация модуля YandexMoney - Yury Glushkov
Презентация модуля YandexMoney - Yury GlushkovDrupalCampDN
 
Drupal and Outer space - Martin Mayer
Drupal and Outer space - Martin MayerDrupal and Outer space - Martin Mayer
Drupal and Outer space - Martin MayerDrupalCampDN
 
Boost your theming skills - Artem Shymko
Boost your theming skills - Artem ShymkoBoost your theming skills - Artem Shymko
Boost your theming skills - Artem ShymkoDrupalCampDN
 
Continious integration - Иван Лещёв
Continious integration - Иван ЛещёвContinious integration - Иван Лещёв
Continious integration - Иван ЛещёвDrupalCampDN
 
Rules - Yaroslav Doroshuk
Rules - Yaroslav DoroshukRules - Yaroslav Doroshuk
Rules - Yaroslav DoroshukDrupalCampDN
 
Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...
Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...
Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...DrupalCampDN
 

Mehr von DrupalCampDN (20)

Drupal - Changing the Web by Connecting Open Minds - Josef Dabernig
Drupal - Changing the Web by Connecting Open Minds - Josef DabernigDrupal - Changing the Web by Connecting Open Minds - Josef Dabernig
Drupal - Changing the Web by Connecting Open Minds - Josef Dabernig
 
Dependency Injection in Drupal 8 - Стадник АндрейQweqwe
Dependency Injection in Drupal 8 - Стадник АндрейQweqweDependency Injection in Drupal 8 - Стадник АндрейQweqwe
Dependency Injection in Drupal 8 - Стадник АндрейQweqwe
 
Our AWS Cloud Journey - Andrew Boag
Our AWS Cloud Journey - Andrew BoagOur AWS Cloud Journey - Andrew Boag
Our AWS Cloud Journey - Andrew Boag
 
Guzzle in Drupal 8 and as a REST client - Артем Мирошник
Guzzle in Drupal 8 and as a REST client - Артем МирошникGuzzle in Drupal 8 and as a REST client - Артем Мирошник
Guzzle in Drupal 8 and as a REST client - Артем Мирошник
 
Blocks & Layouts in D7 - Josef Dabernig
Blocks & Layouts in D7 - Josef DabernigBlocks & Layouts in D7 - Josef Dabernig
Blocks & Layouts in D7 - Josef Dabernig
 
CKEditor в Drupal: тонкая настройка и кастомизация - Osman Seferov
CKEditor в Drupal: тонкая настройка и кастомизация - Osman SeferovCKEditor в Drupal: тонкая настройка и кастомизация - Osman Seferov
CKEditor в Drupal: тонкая настройка и кастомизация - Osman Seferov
 
Drush - use full power - Alexander Schedrov
Drush - use full power - Alexander SchedrovDrush - use full power - Alexander Schedrov
Drush - use full power - Alexander Schedrov
 
Это Drupal, %username%! - Андрей Черноус
Это Drupal, %username%! - Андрей ЧерноусЭто Drupal, %username%! - Андрей Черноус
Это Drupal, %username%! - Андрей Черноус
 
Migrate - new way site upgrade
Migrate - new way site upgradeMigrate - new way site upgrade
Migrate - new way site upgrade
 
Caching on highload Drupal site - Alexander Shumenko
Caching on highload Drupal site - Alexander ShumenkoCaching on highload Drupal site - Alexander Shumenko
Caching on highload Drupal site - Alexander Shumenko
 
Rich Text in Drupal - Вадим Валуев
Rich Text in Drupal - Вадим ВалуевRich Text in Drupal - Вадим Валуев
Rich Text in Drupal - Вадим Валуев
 
May the parallelity be with you! Distributed computing using Erlang language ...
May the parallelity be with you! Distributed computing using Erlang language ...May the parallelity be with you! Distributed computing using Erlang language ...
May the parallelity be with you! Distributed computing using Erlang language ...
 
Panels как философия - Alexander Danilenko
Panels как философия - Alexander DanilenkoPanels как философия - Alexander Danilenko
Panels как философия - Alexander Danilenko
 
DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...
 
Презентация модуля YandexMoney - Yury Glushkov
Презентация модуля YandexMoney - Yury GlushkovПрезентация модуля YandexMoney - Yury Glushkov
Презентация модуля YandexMoney - Yury Glushkov
 
Drupal and Outer space - Martin Mayer
Drupal and Outer space - Martin MayerDrupal and Outer space - Martin Mayer
Drupal and Outer space - Martin Mayer
 
Boost your theming skills - Artem Shymko
Boost your theming skills - Artem ShymkoBoost your theming skills - Artem Shymko
Boost your theming skills - Artem Shymko
 
Continious integration - Иван Лещёв
Continious integration - Иван ЛещёвContinious integration - Иван Лещёв
Continious integration - Иван Лещёв
 
Rules - Yaroslav Doroshuk
Rules - Yaroslav DoroshukRules - Yaroslav Doroshuk
Rules - Yaroslav Doroshuk
 
Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...
Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...
Системы управления взаимоотношениями с клиентами. Drupal CRM Core. - Вадим Ми...
 

Kürzlich hochgeladen

Presentation2.pptx - JoyPress Wordpress
Presentation2.pptx -  JoyPress WordpressPresentation2.pptx -  JoyPress Wordpress
Presentation2.pptx - JoyPress Wordpressssuser166378
 
Computer 10 Lesson 8: Building a Website
Computer 10 Lesson 8: Building a WebsiteComputer 10 Lesson 8: Building a Website
Computer 10 Lesson 8: Building a WebsiteMavein
 
LESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdf
LESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdfLESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdf
LESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdfmchristianalwyn
 
LESSON 10/ GROUP 10/ ST. THOMAS AQUINASS
LESSON 10/ GROUP 10/ ST. THOMAS AQUINASSLESSON 10/ GROUP 10/ ST. THOMAS AQUINASS
LESSON 10/ GROUP 10/ ST. THOMAS AQUINASSlesteraporado16
 
Vision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced Horizons
Vision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced HorizonsVision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced Horizons
Vision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced HorizonsRoxana Stingu
 
Check out the Free Landing Page Hosting in 2024
Check out the Free Landing Page Hosting in 2024Check out the Free Landing Page Hosting in 2024
Check out the Free Landing Page Hosting in 2024Shubham Pant
 
TYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDS
TYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDSTYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDS
TYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDSedrianrheine
 
Benefits of doing Internet peering and running an Internet Exchange (IX) pres...
Benefits of doing Internet peering and running an Internet Exchange (IX) pres...Benefits of doing Internet peering and running an Internet Exchange (IX) pres...
Benefits of doing Internet peering and running an Internet Exchange (IX) pres...APNIC
 
WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024
WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024
WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024Jan Löffler
 
Introduction to ICANN and Fellowship program by Shreedeep Rayamajhi.pdf
Introduction to ICANN and Fellowship program  by Shreedeep Rayamajhi.pdfIntroduction to ICANN and Fellowship program  by Shreedeep Rayamajhi.pdf
Introduction to ICANN and Fellowship program by Shreedeep Rayamajhi.pdfShreedeep Rayamajhi
 
Bio Medical Waste Management Guideliness 2023 ppt.pptx
Bio Medical Waste Management Guideliness 2023 ppt.pptxBio Medical Waste Management Guideliness 2023 ppt.pptx
Bio Medical Waste Management Guideliness 2023 ppt.pptxnaveenithkrishnan
 
Zero-day Vulnerabilities
Zero-day VulnerabilitiesZero-day Vulnerabilities
Zero-day Vulnerabilitiesalihassaah1994
 

Kürzlich hochgeladen (12)

Presentation2.pptx - JoyPress Wordpress
Presentation2.pptx -  JoyPress WordpressPresentation2.pptx -  JoyPress Wordpress
Presentation2.pptx - JoyPress Wordpress
 
Computer 10 Lesson 8: Building a Website
Computer 10 Lesson 8: Building a WebsiteComputer 10 Lesson 8: Building a Website
Computer 10 Lesson 8: Building a Website
 
LESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdf
LESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdfLESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdf
LESSON 5 GROUP 10 ST. THOMAS AQUINAS.pdf
 
LESSON 10/ GROUP 10/ ST. THOMAS AQUINASS
LESSON 10/ GROUP 10/ ST. THOMAS AQUINASSLESSON 10/ GROUP 10/ ST. THOMAS AQUINASS
LESSON 10/ GROUP 10/ ST. THOMAS AQUINASS
 
Vision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced Horizons
Vision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced HorizonsVision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced Horizons
Vision Forward: Tracing Image Search SEO From Its Roots To AI-Enhanced Horizons
 
Check out the Free Landing Page Hosting in 2024
Check out the Free Landing Page Hosting in 2024Check out the Free Landing Page Hosting in 2024
Check out the Free Landing Page Hosting in 2024
 
TYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDS
TYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDSTYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDS
TYPES AND DEFINITION OF ONLINE CRIMES AND HAZARDS
 
Benefits of doing Internet peering and running an Internet Exchange (IX) pres...
Benefits of doing Internet peering and running an Internet Exchange (IX) pres...Benefits of doing Internet peering and running an Internet Exchange (IX) pres...
Benefits of doing Internet peering and running an Internet Exchange (IX) pres...
 
WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024
WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024
WordPress by the numbers - Jan Loeffler, CTO WebPros, CloudFest 2024
 
Introduction to ICANN and Fellowship program by Shreedeep Rayamajhi.pdf
Introduction to ICANN and Fellowship program  by Shreedeep Rayamajhi.pdfIntroduction to ICANN and Fellowship program  by Shreedeep Rayamajhi.pdf
Introduction to ICANN and Fellowship program by Shreedeep Rayamajhi.pdf
 
Bio Medical Waste Management Guideliness 2023 ppt.pptx
Bio Medical Waste Management Guideliness 2023 ppt.pptxBio Medical Waste Management Guideliness 2023 ppt.pptx
Bio Medical Waste Management Guideliness 2023 ppt.pptx
 
Zero-day Vulnerabilities
Zero-day VulnerabilitiesZero-day Vulnerabilities
Zero-day Vulnerabilities
 

Twig internals - Maksym MoskvychevTwig internals maksym moskvychev

  • 3. What is Twig? Maintenance page of Bartik theme. Drupal 7, PHP template Drupal 8, Twig template
  • 4. Why we are here? To remember (or learn) the basics of Twig Recall Twig main features and advantages Find out extending possibilities Debug Twig core a little bit
  • 5. Print data {{ foo }} Twig start points Do something {% for %}
  • 6. Basic syntax strings numbers objects arrays null true false hashes {% for value in Traversable %} {% else %} {% endfor %} {% ifexpression %} {% elseif %} {% endif %} {% else %} -> . ~. Data types Operators Control Structures
  • 7. Functions Tests Filters From Functions to Filters and Tests Functions in Twig works the same as in PHP – they apply arguments in parentheses and return result. Filters are modifying the value by some rules. Value Filter Params Tests are checking the value by test rule. Value Test Paramsis Test sign Filter sign
  • 8. Extending templates Layout block header block footer Blocksidebar block content Module template Blocksidebar extends Your template block content Block definitions in child templates replace its content in parent template You have to define only that blocks that you want to overwrite You can overwrite any block from parent template extends Replaces per block
  • 9. Re-usage of templates Your template Parent template Layout Parent template {% extends … %} Replaces per block Block definitions {% use … %} Peace of template {% include … %} Macro (Peace of template with arguments) {% import … %} {% embed … %}
  • 10. Creating Twig extension class MyExtension extends Twig_Extension { public function getFilters() { return array( new Twig_SimpleFilter(„my_filter', „callback'), ); } } $twig->addExtension(new MyExtension()); Custom extension allows to define: •Globals •Functions •Filters •Tags •Tests •Operators
  • 11. Extending Twig for Jedi Make a service global for twig Create a macro when need to reuse template with parameters Forgot to calculate some stuff before rendering template? - Go to the dark side, make your service global Want to define some logic in declarative way? - Do not restrain your emotions, make a macro For strong minds the only way is to write custom tag, in custom bundle and publish it on GitHub Twig Extension Also you could create a Twig extension to define your functions, filters, tests and operators. And share the extension between projects Custom tag
  • 12. How it works? Data from controller Lexer Parser Compiler Caching system Web page Hello word! index.html.twig Evaluate Lexer splits input text into language primitives in one stream Parser builds node tree according to nesting rules (Abstract Syntax Tree) Compiler generates PHP code based on Abstract syntax Tree Each template is represented as a PHP class in the caching system First time Twig has to parse input file and build cache entry
  • 13. Lexer 1 Hello. 2 {{.name|capitalize.}} 3 For example there is a file index.html.twig Lexer understands language primitives and outputs them in one stream Lexer Hm.. There is some text. TEXT_TYPE(“Hello n”) Hm.. Seems this is start of tag VAR_START_TYPE() TEXT_TYPE(“Hello n”), VAR_START_TYPE(), NAME_TYPE(“name”), OPERATOR_TYPE(“|”), NAME_TYPE(“capitalize”), VAR_END_TYPE(), EOF_TYPE() Now I see a variable NAME_TYPE(“name”) Hm.. Some operator OPERATOR_TYPE(“|”) Wow! Again some name NAME_TYPE(“capitalize”)
  • 14. Parser Parser TEXT_TYPE(“Hello n”), VAR_START_TYPE(), NAME_TYPE(“name”), OPERATOR_TYPE(“|”), NAME_TYPE(“capitalize”), VAR_END_TYPE(), EOF_TYPE() Template: index.html.twig Text: “Hello n” Echo result of calculation Filter: capitalize Value of variable “name” The goal of parser is to find dependencies between elements. It understands that one thing can contain others. At the end if builds the whole document in object- oriented way when one objects consist of other.
  • 15. Compiler Template: index.html.twig Text: “Hello n” Echo result of calculation Filter: capitalize Value of variable “name” Compiler is a tool that converts Abstract Syntax Tree into a PHP code. For each type of node compiler has own handlers. Each handler knows how to transform node of AST into raw PHP string. So, at the output we have PHP code in one stream. Compiler echo “Hello n”; echo ucfirst($name); This code will be put into PHP representation of index.html.twig
  • 16. The power of customization Lexer Goals Solutions As a PHP lover I want to support <?: ?> tags so that it makes me happy As an idealist I need {% single %} case in “for” tag So that it controls case when there is only one element in input data As a “hot fixer” I want to have {% log %} tag so that I can save data between tags into log file Parser Compiler Create a node class that implements Twig_NodeInterface. Define custom logic in compile() method. You also need to create custom TokenParser to initialize new node class. Create a Token Parser class that implements Twig_TokenParserInterface. Define you logic in parse() method. Use existing compilers for all cases. Change default Twig lexer with custom one that extends from core and understands new tags as {{ and }}
  • 17. Sandbox – include untrusted templates Secure template include Users can edit templates online ? They can do something you wouldn’t like Let’s filter user’s input by white-list rules! In sandboxed template you can use only allowed: •Methods of your classes, •Properties of your classes •Filters •Tags
  • 18. Find your reason to love Twig Twig is a modern template engine for PHP Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum. Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design. Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.
  • 19. Thank you My contacts: Skype name: maxim_432 Email: maksym.moskvychev@gmail.com