SlideShare a Scribd company logo
USING TWIG
WITH DRUPAL
7
About Me
 I'm the founder and CEO of Exove
 Currently also chairman of board of Drupal
Finland, and member of board of Drupal Estonia
 Global track chair for DrupalConAmsterdam
 Coding experience from 1984, nowadays mostly
in JavaScript and PHP
 Father of three adorable kids
Exove in Brief
ExoveisaleadingNorthernEuropeancompanyspecialisinginopen
sourcewebservicesdesignanddevelopment.
WehelpcompaniesconductbetterbusinessontheInternet
throughbest-of-breedpersonnelandsolutions.
Quickfacts:
 Founded2006
 Over70people
 Servedmorethan170clients
 OfficesinFinland,Estonia,andtheUK
 Solidfinancialstatus
AND THEN TO
THE TOPIC!
All that Twig
goodness in Drupal
8…
…is not yet
released.
Twig.js to Resque
 Twig.js is an independent JavaScript port of
PHPTwig template engine
 It implements most (but not all) features of Twig
 It can be extended
 Available at https://github.com/justjohn/twig.js/
 There is also another JS port called Swig
My Practical Experiences
with Twig.js
 I've implemented numerous templates with Twig.js
 Used always official Twig documentation as reference
 Had no issues with syntax – on the other hand, I have not
needed the most advanced parts of Twig
 Excellent rendering speeds, practically instanteous
responses
 Allows parts of user interface to be regenerated after
changes in data instead of modifying DOM with jQuery
 Makes JS code cleaner
 Works well on desktop, pad and mobile browsers
HOW TO USE
TWIG.JS WITH
DRUPAL?
Prerequisites
1. Twig.js needs to be included in the page
2. Twig template(s) must be loaded and compiled
3. There needs to be some data to be rendered
with the template
4. The results of a template rendering needs to be
inserted into DOM
In Practice
Drupal
HTMLpage
Twig.js Twig
template
d7Twig.js HTML
snippet
1.Drupalemits
anHTMLpage
2.Pageloads
Twig.js
3.Pageexecutes
JScodetorender
data
5.Codeloads
Twigtemplate
6.Coderenders
datawith
templateinto
HTMLsnippet
7.Codeinjectssnippetbacktopage
DataAPI
4.Codeloads
dataforrendering
Initialisation
(function ($) {
Drupal.behaviors.d7Twig = {
attach: function(context, settings) {
if(typeof settings.d7Twig !='undefined') {
d7Twig.init(settings.d7Twig);
}
}
};
Providesettings
fromDrupaltoJS
classcontrolling
Twig.js
Our Twig Handler Class
var d7Twig = {
loadedTemplates: {},
initialised: false,
…
init: function(settings) {
if(this.initialised) {
return;
}
this.initialised = true;
var self = this;
…
}
Initialisetheclass
onlyonce.
Templatestorage/
cache.
Data from Drupal through
Settings
this.d7Bridge = settings;
if(typeof this.d7Bridge != 'undefined') {
if(this.d7Bridge.userAccount) {
…
}
}
Settingsobjectfrom
Drupal.
InitialiseonlyifDrupalhas
providedanuseraccountto
JavaScript.
Actions Bound to DOM Ids
if(this.d7Bridge.userAccount) {
if($('#myScores').length > 0) {
this.showScores();
}
if($('#myGames').length > 0) {
this.showGames();
}
…
}
LaunchJS
functionsbasedon
certainIDsonthe
page.
Template Loading and
Location
 Templates are loaded using anAJAX get call
when needed and stored in compiled form
 Their location needs to be known by the script
 Use static location -> bad idea
 Make Drupal pass the location -> better, but requires
custom coding at Drupal or storing the value
somewhere
 Store templates relatively to the script loading them
-> best value for money
Template Loader
loadTemplate:function(tmpl){
if(this.loadedTemplates[tmpl]==true){
return;
}
varself=this;
$.each(this.templates,function(i,v){
if(v.id==tmpl){
v.href=self.getScriptPath()+v.href;
twig(v);
self.loadedTemplates[v.id]=true;
}
});
}
Compiletemplate;Twig
automatically storesthe
templatewithitsid.
Calculate Script Path
getScriptPath:function(){
if(this.scriptPath){
returnthis.scriptPath;
}
varscripts=document.getElementsByTagName('SCRIPT');
if(scripts&&scripts.length>0){
for(variinscripts){
if(scripts[i].src&&
scripts[i].src.match(/d7twig.js/)){
this.scriptPath=scripts[i].src.
replace(/(.*)d7twig.js(.*)/,'$1');
break;
}
}
}
returnthis.scriptPath;
Findthisscriptand
useitspath.
Template Definitions
templates: [{
id: 'games',
href: 'twig/gameslist.twig',
async: false
}, {
id: 'scores',
href: 'twig/scoreslist.twig',
async: false
}, … RelativetotheJSfile.
Rendering Templates
 Template rendering requires three components
 Compiled template
 Data to be shown
 Insertion point in the DOM
Rendering a Template
render: function(tmpl, dt, jq) {
this.loadTemplate(tmpl);
var mainHtml = twig({ref: tmpl}).render(dt);
$(jq).html(mainHtml);
} Templateidin
templatesobject
(previouscode slide)
Variations of the Theme
renderAppend: function(tmpl,dt,jq){
this.loadTemplate(tmpl);
varmainHtml=twig({ref:tmpl}).render(dt);
$(jq).append(mainHtml);
}
renderReplace:function(tmpl,dt,jq){
this.loadTemplate(tmpl);
varmainHtml=twig({ref:tmpl}).render(dt);
$(jq).replaceWith(mainHtml);
}
renderToString: function(tmpl,dt){
this.loadTemplate(tmpl);
returntwig({ref:tmpl}).render(dt);
}
Where to Get the Data?
 Data is a JavaScript object, so you can create it
anyhow you like
 Typical choice is to get JSON object usingAJAX
call
 Another one is to publish JS variables in Drupal
and use them
 Make sure that they are in the same context as your
class or in global context
 Data could be also read from the page DOM
Using the System
showScores: function() {
var self = this;
var statsUrl = this.d7Bridge.ajaxBaseUrl +
'api/getscores/' +
this.d7Bridge.userAccount;
$.get(statsUrl, function(dt) {
if(dt) {
dt = $.parseJSON(dt);
if(dt.scores) {
self.render('scores', dt,
'#userScores');
Loadandparsedata.
Renderthetemplate
withthedata.
Notes
 There are no error checks, for example, for non-
existing templates
 Template loading adds latency that might not be
desired
 If you use only a couple of templates, you could load
them in init
 Another option is to load them in a single bunch
Multiple Templates in a
Single File
<script type="text/x-twig-template" id="gameslist">
…
</script>
<script type="text/x-twig-template"
id="scoreslist">
…
</script>
Templatecontent
goeshere.
Idforreferringtothe
templateinthecode.
Compiling Them
$.get(templateLocation, function(doc) {
var tmpls = $(doc).
filter('script[type="text/x-twig-template"]');
_.each(tmpls, function(tmpl) {
var tpl = twig({
id: tmpl.id,
data: tmpl.text
});
});
}
Splitthedocument
intoseparatescript
tags.
Compilescripttags'
content.
QUICK DEMO
Recap
 This is not a replacement for Drupal's templating
system – unfortunately
 But it complements it nicely
 Allows moving some template rendering to browser
 Performance boost due to less processing and less
transmitted data
 Could be used to separate user specific and generic
content, allowing better cacheability and use of Varnish
 Makes creating dynamic user interfaces much
easier
THANK YOU!
Questions? Comments?

More Related Content

ZIP
Object Oriented PHP5
PPTX
Mongodb hackathon 02
PDF
[A 3]Javascript oop for xpages developers - public
PDF
A Gentle Introduction To Object Oriented Php
PDF
Drupalcamp Nantes - Apprendre et prendre en main drupal
PDF
Drupal 8 templating with twig
PDF
PPTX
Drupal as a data server
Object Oriented PHP5
Mongodb hackathon 02
[A 3]Javascript oop for xpages developers - public
A Gentle Introduction To Object Oriented Php
Drupalcamp Nantes - Apprendre et prendre en main drupal
Drupal 8 templating with twig
Drupal as a data server

Similar to Using Twig with Drupal 7 (20)

PDF
Building a Custom Theme in Drupal 8
PDF
Twig & D8 - DrupalCamp Baltics 2013 - Tallinn
PDF
Drupal 8 theming deep dive
PDF
Drupal8 themingdeepdive drupaldevdays-montpellier17042015
PDF
Twig for Drupal 8 and PHP | Presented at OC Drupal
PPTX
Ready. Set. Drupal! An Intro to Drupal 8, Part 2
PDF
Backbone js in drupal core
PDF
Drupal 8 deeper dive
PDF
Drupal 8: frontend development
PPT
Powerful and flexible templates with Twig
PDF
JQuery In Drupal
PDF
Mastering Drupal 8’s Twig
PDF
Drupal 8 - Core and API Changes
PPTX
Oleg Bogut - Decoupled Drupal: how to build stable solution with JSON:API, Re...
PPT
DrupalCon Chicago 2011 ReportBack (11/03/30 - G. Bedford)
PDF
Drupal 8 - Corso frontend development
KEY
Twig for Drupal @ Frontendunited Amsterdam 2012
KEY
Drupal 6 JavaScript and jQuery
PPT
jQuery and_drupal
PDF
JavaScript the Smart Way - Getting Started with jQuery
Building a Custom Theme in Drupal 8
Twig & D8 - DrupalCamp Baltics 2013 - Tallinn
Drupal 8 theming deep dive
Drupal8 themingdeepdive drupaldevdays-montpellier17042015
Twig for Drupal 8 and PHP | Presented at OC Drupal
Ready. Set. Drupal! An Intro to Drupal 8, Part 2
Backbone js in drupal core
Drupal 8 deeper dive
Drupal 8: frontend development
Powerful and flexible templates with Twig
JQuery In Drupal
Mastering Drupal 8’s Twig
Drupal 8 - Core and API Changes
Oleg Bogut - Decoupled Drupal: how to build stable solution with JSON:API, Re...
DrupalCon Chicago 2011 ReportBack (11/03/30 - G. Bedford)
Drupal 8 - Corso frontend development
Twig for Drupal @ Frontendunited Amsterdam 2012
Drupal 6 JavaScript and jQuery
jQuery and_drupal
JavaScript the Smart Way - Getting Started with jQuery
Ad

More from Exove (20)

PDF
Drupalcamp Finland – Measuring Front-end Energy Consumption
PDF
Data security in the age of GDPR – most common data security problems
PDF
Provisioning infrastructure to AWS using Terraform – Exove
PDF
Advanced custom fields in Wordpress
PDF
Introduction to Robot Framework – Exove
PDF
Jenkins and visual regression – Exove
PDF
Server-side React with Headless CMS – Exove
PDF
WebSockets in Bravo Dashboard – Exove
PDF
Diversity in recruitment
PDF
Saavutettavuus liiketoimintana
PDF
Saavutettavuus osana Eläkeliiton verkkosivu-uudistusta
PDF
Mitä saavutettavuusdirektiivi pitää sisällään
PDF
Creating Landing Pages for Drupal 8
PDF
GDPR for developers
PDF
Managing Complexity and Privacy Debt with Drupal
PDF
Life with digital services after GDPR
PDF
GDPR - no beginning no end
PDF
Developing truly personalised experiences
PDF
Customer Experience and Personalisation
PDF
Adventures In Programmatic Branding – How To Design With Algorithms And How T...
Drupalcamp Finland – Measuring Front-end Energy Consumption
Data security in the age of GDPR – most common data security problems
Provisioning infrastructure to AWS using Terraform – Exove
Advanced custom fields in Wordpress
Introduction to Robot Framework – Exove
Jenkins and visual regression – Exove
Server-side React with Headless CMS – Exove
WebSockets in Bravo Dashboard – Exove
Diversity in recruitment
Saavutettavuus liiketoimintana
Saavutettavuus osana Eläkeliiton verkkosivu-uudistusta
Mitä saavutettavuusdirektiivi pitää sisällään
Creating Landing Pages for Drupal 8
GDPR for developers
Managing Complexity and Privacy Debt with Drupal
Life with digital services after GDPR
GDPR - no beginning no end
Developing truly personalised experiences
Customer Experience and Personalisation
Adventures In Programmatic Branding – How To Design With Algorithms And How T...
Ad

Recently uploaded (20)

PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Big Data Technologies - Introduction.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Assigned Numbers - 2025 - Bluetooth® Document
Dropbox Q2 2025 Financial Results & Investor Presentation
Advanced methodologies resolving dimensionality complications for autism neur...
20250228 LYD VKU AI Blended-Learning.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation theory and applications.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
The AUB Centre for AI in Media Proposal.docx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Big Data Technologies - Introduction.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
MIND Revenue Release Quarter 2 2025 Press Release
sap open course for s4hana steps from ECC to s4
Network Security Unit 5.pdf for BCA BBA.
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11

Using Twig with Drupal 7