SlideShare a Scribd company logo
1 of 25
Download to read offline
Mastering

Drupal 8’s Twig
John Albin Wilkins

November 24, 2017
Twig
http://twig.sensiolabs.org/
Twig for Template Designers

https://twig.symfony.com/doc/1.x/templates.html
DRUPAL 8
TWIG
Built-in Drupal templates
use ~30% of the
available Twig features.
Drupal 8.4.2 has Twig 1.32.0
Why Twig?
Modern Syntax
<?php	print	variable;	?>	
{{	variable	}}
Drupal 7:
Twig:
Where's the

performance hit?
<?php if ($is_true): ?> <b>TRUE!</b> <?php endif; ?>
PHP parser/compiler has to context switch
Twig

compiles templates
into PHP classes
Twig syntax
{{	variable	}}	
{#	comment	#}	
{%	command	%}
Variable drilling
{{	variable.thing	}}	
{{	page.primary_menu	}}	
{{	comment.owner.anonymous	}}
This is how Twig resolves complex variables
<nav>{{ content.links }}</nav>
!
$content['links']
$content->links
$content->links()
$content->getLinks()
$content->isLinks()
null
Twig tries all these alternatives
and uses the first one that exists.
Some Drupal variables names are special
!
$variables['site_slogan']['#markup'] = ...
!
{{ site_slogan.#markup }}
core/themes/bartik/bartik.theme
This doesn't work because
of the # character
{{ site_slogan['#markup'] }}
{{ attribute(site_slogan, '#markup') }}
Improving Twig performance
• Twig provides a PHP extension.
• This extension only implements
the variable resolving logic.
• See twig.sensiolabs.org/doc/
installation.html#installing-the-
c-extension
EXPECTED

PERFORMANCE
INCREASE
15%
Twig filters

(added by Twig)
{{	variable|escape('html')	}}	
{{	variable|e('html')	}}	
Also accepts: 'js', 'css', 'url', 'html_attr'
{{	variable|raw	}}	
collections: |keys			|first			|last			|length
{{	variable|date('Y-m-d')	}}

{{	'now'|date(timezone=user.timezone)	}}
http://twig.sensiolabs.org/doc/filters/index.html
Drupal

auto-escapes

by default!
Twig filters

(added by Drupal)
{{	variable|safe_join(',	')	}}	
{{	variable|without('something')	}}	
{{	variable|clean_class	}}

{{	variable|clean_id	}}	
{{	variable|format_date('medium')	}}	
{{	'Some	string'|t	}}
https://www.drupal.org/node/2357633
Translation
{{	'a	string'|t	}}

{{	'a	string'|trans	}}
{%	trans	%}

		Submitted	by	{{	author_name	}}

		on	{{	date	}}

{%	endtrans	%}
Attribute object
{{	attributes.addClass('foo')	}}	
{{	attributes.removeClass('bar')	}}	
{%	if	attributes.hasClass('thing')	%}	
{{	attributes.setAttribute('id',	'thing')	}}	
{{	attributes.removeAttribute('id')	}}
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!
Template!Attribute.php/class/Attribute/8
Control directives
{%	if	thing	%}

		

{%	endif	%}	
{%	for	user	in	users	%}

		...

{%	else	%}

		There	is	no	spoon.

{%	endfor	%}	
{%	for	item	in	collection	if	item.published	%}
Control directives
{%	for	row	in	images|batch(3)	%}

		<div	class="row">

				{%	for	image	in	row	%}

						<div	class="image">

								<img	src=""	alt=""	>

						</div>

				{%	endfor	%}

		</div>

{%	endfor	%}
Extends
{%	extends	"region.html.twig"	%}	
{%	set	attributes	=	attributes.addClass('clearfix')	%}
bartik/templates/region--header.html.twig:
classy/templates/layout/region.html.twig:
{%	
		set	classes	=	[	
				'region',	
				'region-'	~	region|clean_class,	
		]	
%}	
<div{{	attributes.addClass(classes)	}}>	
		{{	content	}}	
</div>
Extends
{%	extends	"block.html.twig"	%}	
{%	block	content	%}	
		<a	href="{{	path('<front>')	}}"	rel="home">	
				<img	src="{{	site_logo	}}"	alt="{{	'Home'|t	}}"	/>	
		</a>	
{%	endblock	%}
classy/templates/block/block--system-branding-block.html.twig:
classy/templates/block/block.html.twig:
<div{{	attributes.addClass(classes)	}}>	
		<h2{{	title_attributes	}}>{{	label	}}</h2>	
		{%	block	content	%}	
				{{	content	}}	
		{%	endblock	%}	
</div>
Include
{%	include	'@my_theme/grid_3.twig'	%}	
{%	include	'@my_theme/grid_3.twig'	with	{

				var1:	"a	new	value",

				var2:	anotherVar,

		}	only

%}
Embed
{%	embed	'@my_theme/grid_3.twig'	%}

		{%	block	column1	%}

				…block	contents…

		{%	endblock	%}

{%	endembed	%}
Debugging
In sites/default, copy default.services.yml

to services.yml.
Look for these lines and change "false" to "true".

twig.config:

		debug:	false
https://www.drupal.org/node/1906392
Libraries
(adding CSS & JS)
my_theme.libraries.yml:



breadcrumb:

		css:

				component:

						components/breadcrumb/breadcrumb.css:	{}

		dependencies:

				-	my_theme/visually-hidden
https://www.drupal.org/node/2216195
What else?
Drupal 8 Theme Guide:

www.drupal.org/theme-guide/8

More Related Content

Similar to Mastering Drupal 8’s Twig

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
Fabien Potencier
 
Drupal 8 templating with twig
Drupal 8 templating with twigDrupal 8 templating with twig
Drupal 8 templating with twig
Taras Omelianenko
 
Future proofing design work with Web components
Future proofing design work with Web componentsFuture proofing design work with Web components
Future proofing design work with Web components
btopro
 
Introduction To Drupal
Introduction To DrupalIntroduction To Drupal
Introduction To Drupal
Lauren Roth
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
Ralph Schindler
 

Similar to Mastering Drupal 8’s Twig (20)

Twig: Friendly Curly Braces Invade Your Templates!
Twig: Friendly Curly Braces Invade Your Templates!Twig: Friendly Curly Braces Invade Your Templates!
Twig: Friendly Curly Braces Invade Your Templates!
 
Twig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC DrupalTwig for Drupal 8 and PHP | Presented at OC Drupal
Twig for Drupal 8 and PHP | Presented at OC Drupal
 
Extending Twig
Extending TwigExtending Twig
Extending Twig
 
Building Drupal 8 Sites
Building Drupal 8 SitesBuilding Drupal 8 Sites
Building Drupal 8 Sites
 
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
 
DevOps is Going to Replace SDLC! Learn Why?
DevOps is Going to Replace SDLC! Learn Why?DevOps is Going to Replace SDLC! Learn Why?
DevOps is Going to Replace SDLC! Learn Why?
 
Dev ops webinar 5 aug 15
Dev ops webinar 5 aug 15Dev ops webinar 5 aug 15
Dev ops webinar 5 aug 15
 
Drupal 8 templating with twig
Drupal 8 templating with twigDrupal 8 templating with twig
Drupal 8 templating with twig
 
Best Practice Site Architecture in Drupal 8
Best Practice Site Architecture in Drupal 8Best Practice Site Architecture in Drupal 8
Best Practice Site Architecture in Drupal 8
 
Webinar: DevOps - Redefining your IT Strategy
Webinar: DevOps - Redefining your IT StrategyWebinar: DevOps - Redefining your IT Strategy
Webinar: DevOps - Redefining your IT Strategy
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
Flux: A modern way of doing MVC?
Flux: A modern way of doing MVC?Flux: A modern way of doing MVC?
Flux: A modern way of doing MVC?
 
Twig in drupal8
Twig in drupal8Twig in drupal8
Twig in drupal8
 
DrupalTour. Rivne — Drupal 8 (Ivan Tibezh, InternetDevels)
DrupalTour. Rivne — Drupal 8 (Ivan Tibezh, InternetDevels)DrupalTour. Rivne — Drupal 8 (Ivan Tibezh, InternetDevels)
DrupalTour. Rivne — Drupal 8 (Ivan Tibezh, InternetDevels)
 
Being Dangerous with Twig
Being Dangerous with TwigBeing Dangerous with Twig
Being Dangerous with Twig
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
Drupal8 render pipeline
Drupal8 render pipelineDrupal8 render pipeline
Drupal8 render pipeline
 
Future proofing design work with Web components
Future proofing design work with Web componentsFuture proofing design work with Web components
Future proofing design work with Web components
 
Introduction To Drupal
Introduction To DrupalIntroduction To Drupal
Introduction To Drupal
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
 

More from John Albin Wilkins

More from John Albin Wilkins (20)

Using the CSS Nesting Spec Today
Using the CSS Nesting Spec TodayUsing the CSS Nesting Spec Today
Using the CSS Nesting Spec Today
 
The Drupal Roadmap: From D7 to D9
The Drupal Roadmap: From D7 to D9The Drupal Roadmap: From D7 to D9
The Drupal Roadmap: From D7 to D9
 
CSS-in-JS: unexpected lessons for Drupal component design
CSS-in-JS: unexpected lessons for Drupal component designCSS-in-JS: unexpected lessons for Drupal component design
CSS-in-JS: unexpected lessons for Drupal component design
 
Style Guide Driven Development: All Hail the Robot Overlords!
Style Guide Driven Development: All Hail the Robot Overlords!Style Guide Driven Development: All Hail the Robot Overlords!
Style Guide Driven Development: All Hail the Robot Overlords!
 
Styleguide-Driven Development: The New Web Development
Styleguide-Driven Development: The New Web DevelopmentStyleguide-Driven Development: The New Web Development
Styleguide-Driven Development: The New Web Development
 
Managing Complex Projects with Design Components - Drupalcon Austin 2014
Managing Complex Projects with Design Components - Drupalcon Austin 2014Managing Complex Projects with Design Components - Drupalcon Austin 2014
Managing Complex Projects with Design Components - Drupalcon Austin 2014
 
DrupalSouth 2014: Managing Complex Projects with Design Components
DrupalSouth 2014: Managing Complex Projects with Design ComponentsDrupalSouth 2014: Managing Complex Projects with Design Components
DrupalSouth 2014: Managing Complex Projects with Design Components
 
SassConf: Managing Complex Projects with Design Components
SassConf: Managing Complex Projects with Design ComponentsSassConf: Managing Complex Projects with Design Components
SassConf: Managing Complex Projects with Design Components
 
Drupal Camp Taipei Keynote
Drupal Camp Taipei KeynoteDrupal Camp Taipei Keynote
Drupal Camp Taipei Keynote
 
Become an IA superstar (Chinese version)
Become an IA superstar (Chinese version)Become an IA superstar (Chinese version)
Become an IA superstar (Chinese version)
 
Mobile drupal: building a mobile theme
Mobile drupal: building a mobile themeMobile drupal: building a mobile theme
Mobile drupal: building a mobile theme
 
Sass: CSS with Attitude
Sass: CSS with AttitudeSass: CSS with Attitude
Sass: CSS with Attitude
 
Mastering zen
Mastering zenMastering zen
Mastering zen
 
Drupal and the Future of the Web
Drupal and the Future of the WebDrupal and the Future of the Web
Drupal and the Future of the Web
 
What's new in D7 Theming?
What's new in D7 Theming?What's new in D7 Theming?
What's new in D7 Theming?
 
Default theme implementations: a guide for module developers that want sweet ...
Default theme implementations: a guide for module developers that want sweet ...Default theme implementations: a guide for module developers that want sweet ...
Default theme implementations: a guide for module developers that want sweet ...
 
Rocking the Theme Layer
Rocking the Theme LayerRocking the Theme Layer
Rocking the Theme Layer
 
Drupal Design Tips
Drupal Design TipsDrupal Design Tips
Drupal Design Tips
 
New Adventures in Drupal Theming
New Adventures in Drupal ThemingNew Adventures in Drupal Theming
New Adventures in Drupal Theming
 
Nanocon Taiwan
Nanocon TaiwanNanocon Taiwan
Nanocon Taiwan
 

Recently uploaded

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 

Mastering Drupal 8’s Twig