• Save
Using Twig with Drupal 7
 

Using Twig with Drupal 7

on

  • 555 views

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

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

Statistics

Views

Total Views
555
Views on SlideShare
411
Embed Views
144

Actions

Likes
1
Downloads
0
Comments
0

6 Embeds 144

https://twitter.com 76
http://www.exove.com 48
http://silver.exove.net 12
http://localhost 4
http://www.slideee.com 2
http://exove.lol 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Using Twig with Drupal 7 Using Twig with Drupal 7 Presentation Transcript

  • 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?