Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
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 D...
Exove in Brief
ExoveisaleadingNorthernEuropeancompanyspecialisinginopen
sourcewebservicesdesignanddevelopment.
Wehelpcompa...
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...
My Practical Experiences
with Twig.js
 I've implemented numerous templates with Twig.js
 Used always official Twig docum...
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 t...
In Practice
Drupal
HTMLpage
Twig.js Twig
template
d7Twig.js HTML
snippet
1.Drupalemits
anHTMLpage
2.Pageloads
Twig.js
3.Pa...
Initialisation
(function ($) {
Drupal.behaviors.d7Twig = {
attach: function(context, settings) {
if(typeof settings.d7Twig...
Our Twig Handler Class
var d7Twig = {
loadedTemplates: {},
initialised: false,
…
init: function(settings) {
if(this.initia...
Data from Drupal through
Settings
this.d7Bridge = settings;
if(typeof this.d7Bridge != 'undefined') {
if(this.d7Bridge.use...
Actions Bound to DOM Ids
if(this.d7Bridge.userAccount) {
if($('#myScores').length > 0) {
this.showScores();
}
if($('#myGam...
Template Loading and
Location
 Templates are loaded using anAJAX get call
when needed and stored in compiled form
 Their...
Template Loader
loadTemplate:function(tmpl){
if(this.loadedTemplates[tmpl]==true){
return;
}
varself=this;
$.each(this.tem...
Calculate Script Path
getScriptPath:function(){
if(this.scriptPath){
returnthis.scriptPath;
}
varscripts=document.getEleme...
Template Definitions
templates: [{
id: 'games',
href: 'twig/gameslist.twig',
async: false
}, {
id: 'scores',
href: 'twig/s...
Rendering Templates
 Template rendering requires three components
 Compiled template
 Data to be shown
 Insertion poin...
Rendering a Template
render: function(tmpl, dt, jq) {
this.loadTemplate(tmpl);
var mainHtml = twig({ref: tmpl}).render(dt)...
Variations of the Theme
renderAppend: function(tmpl,dt,jq){
this.loadTemplate(tmpl);
varmainHtml=twig({ref:tmpl}).render(d...
Where to Get the Data?
 Data is a JavaScript object, so you can create it
anyhow you like
 Typical choice is to get JSON...
Using the System
showScores: function() {
var self = this;
var statsUrl = this.d7Bridge.ajaxBaseUrl +
'api/getscores/' +
t...
Notes
 There are no error checks, for example, for non-
existing templates
 Template loading adds latency that might not...
Multiple Templates in a
Single File
<script type="text/x-twig-template" id="gameslist">
…
</script>
<script type="text/x-t...
Compiling Them
$.get(templateLocation, function(doc) {
var tmpls = $(doc).
filter('script[type="text/x-twig-template"]');
...
QUICK DEMO
Recap
 This is not a replacement for Drupal's templating
system – unfortunately
 But it complements it nicely
 Allows m...
THANK YOU!
Questions? Comments?
Upcoming SlideShare
Loading in …5
×

Using Twig with Drupal 7

1,456 views

Published on

How to use Twig in Drupal 7 by employing Twig.js and JavaScript code.

Published in: Technology, Business
  • Be the first to comment

Using Twig with Drupal 7

  1. 1. USING TWIG WITH DRUPAL 7
  2. 2. 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
  3. 3. Exove in Brief ExoveisaleadingNorthernEuropeancompanyspecialisinginopen sourcewebservicesdesignanddevelopment. WehelpcompaniesconductbetterbusinessontheInternet throughbest-of-breedpersonnelandsolutions. Quickfacts:  Founded2006  Over70people  Servedmorethan170clients  OfficesinFinland,Estonia,andtheUK  Solidfinancialstatus
  4. 4. AND THEN TO THE TOPIC!
  5. 5. All that Twig goodness in Drupal 8…
  6. 6. …is not yet released.
  7. 7. 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
  8. 8. 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
  9. 9. HOW TO USE TWIG.JS WITH DRUPAL?
  10. 10. 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
  11. 11. 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
  12. 12. Initialisation (function ($) { Drupal.behaviors.d7Twig = { attach: function(context, settings) { if(typeof settings.d7Twig !='undefined') { d7Twig.init(settings.d7Twig); } } }; Providesettings fromDrupaltoJS classcontrolling Twig.js
  13. 13. 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.
  14. 14. Data from Drupal through Settings this.d7Bridge = settings; if(typeof this.d7Bridge != 'undefined') { if(this.d7Bridge.userAccount) { … } } Settingsobjectfrom Drupal. InitialiseonlyifDrupalhas providedanuseraccountto JavaScript.
  15. 15. 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.
  16. 16. 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
  17. 17. 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.
  18. 18. 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.
  19. 19. Template Definitions templates: [{ id: 'games', href: 'twig/gameslist.twig', async: false }, { id: 'scores', href: 'twig/scoreslist.twig', async: false }, … RelativetotheJSfile.
  20. 20. Rendering Templates  Template rendering requires three components  Compiled template  Data to be shown  Insertion point in the DOM
  21. 21. 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)
  22. 22. 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); }
  23. 23. 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
  24. 24. 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.
  25. 25. 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
  26. 26. 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.
  27. 27. 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.
  28. 28. QUICK DEMO
  29. 29. 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
  30. 30. THANK YOU! Questions? Comments?

×