SlideShare une entreprise Scribd logo
1  sur  36
Télécharger pour lire hors ligne
$.template
Why use a template?

• Render data as markup

• Separation of display logic from
  business logic

• Reusable markup (in theory)

• Maybe it’s cleaner?

• It’s definitely faster than...
The Other Options

• String Concatenation

• Array.join

• DOM Manipulation

• jQuery.append
String Concatenation
  var str = '';

str += '<p>Hello, <em>';
str += this.name;
str += '</em>!</p>';

body.innerHTML = str;
Array.join
 var arr = [];

 arr.push('<p>Hello, <em>');
 arr.push(this.name);
 arr.push('</em>!</p>');

 body.innerHTML = arr.join('');
DOM Manipulation
  var p     = document.createElement('P');

var hello = document.createTextNode('Hello, ');

var em    = document.createElement('EM');
var world = document.createTextNode(this.name + '!');

em.appendChild(world);

p.appendChild(hello);
p.appendChild(world);

body.appendChild(p);
jQuery.append
 $('<p>').append(
   'Hello, ',
   $('<em>').text(this.name + '!')
 ).appendTo('body');
JavaScript Templating
Libraries

• mustache.js

• HandlebarJS

• TrimPath JST

• Resig Micro-Templating

• jQuery.template
$.template

• jQuery plugin

• Modified Resig Micro-
  Templating

• Allows inline JavaScript

• Caching

• Ajax

• Faster
$.template Basics

• Converts a string into a function

• Caches the rendered function

• Function renders data as DOM/
  HTML
Writing a template
Scope (this)

• Rendered template function is executed in the scope of
  the data object

• Dropped with for performance, replaced with this
var str   = '<p>Hello, <em>{%= this.name %}!</em></p>';
Two Types of Tags

• Output tags pass their values to
  the returned output

• Functional tags execute
  arbitrary JavaScript, but do not
  output any value
Output Tags {%= ... %}
// Output is added to the output
{%= this.property %}

// Ternaries can be used for quick conditionals
{%= this.property ? this.property : "N/A" %}

// JavaScript is executed and added to output
{%= (new Date()).getTime() - (this.birthdate).getTime() %}
Functional Tags {% ... %}
// Value is not added to output
{% var pie = 22/7; }

// Semi-colons not required, but encouraged for best practice
{% var greeting = "Hello, " + this.name }
// WIN

// Double-quotes are STRICTLY REQUIRED
{% var greeting = 'Hello, ' + this.name }
// FAIL

// Single-quotes allowed in strings
{% var greeting = "I'm with " + this.name }
// WIN
Looping an Array
{% for (var i = 0, n = this.images.length; i < n; ++i) { %}
  {% var img = this.images[i]; }
  <img src="{%= img.src %}" alt="{%= img.description %}">
{% } %}
Conditionals
{% if (this.age > 21) { %}
  <a href="booze.html">Drink up!</a>
{% } else { %}
  <a href="music.html">Enjoy some tunes!</a>
{% } %}
Subtemplates
<h1>{%= this.name %}</h1>

{% function renderJob (job) { %}
  {% var verb = (job.end === "present") ? "work" : "worked"; %}

 I {%= verb %} at <strong>{%= job.company %}</strong> as a
 <em>{%= job.position %}</em>

{% } %}

<ul>
  {% for (var i = 0, n = this.jobs.length; i < n; ++i) { %}
     <li>{% renderJob(this.jobs[i]) %}</li>
  {% } %}
</ul>
Subtemplates
<h1>{%= this.name %}</h1>

{% function renderJob (job) { %}
  {% var verb = (job.end === "present") ? "work" : "worked"; %}

 I {%= verb %} at <strong>{%= job.company %}</strong> as a
 <em>{%= job.position %}</em> {% renderDate(job.start, job.end) %}

  {% function renderDate (start, end) { %}
    from {%= start %} {%= end === "present" ? "" : "to " + end %}.
  {% } %}
{% } %}

<ul>
  {% for (var i = 0, n = this.jobs.length; i < n; ++i) { %}
     <li>{% renderJob(this.jobs[i]) %}</li>
  {% } %}
</ul>
template + data = output
Template Input

• string

  • var

  • $.ajax (asynchronous)

• DOM (via $.fn.template)

• Ajax (synchronous)
Template Input (string)
var str   = '<p>Hello, <em>{%= this.name %}!</em></p>';

var data = { name: 'world' };

var func = $.template(str);
// anonymous()

var elem = $.template(str, data);
// [jquery:template]

var html = $.template(str, data, true);
// <p>Hello, <em>world!</em></p>
Template Input (DOM)
<script id="tpl" type="text/html">
Hello, {%= this.name %}!
</script>

var data = { name: 'world' };

var func = $('#tpl').template();
// anonymous()

var elem = $('#tpl').template(data);
// [jquery:template]

var html = $('#tpl').template(data, true);
// <p>Hello, <em>world!</em></p>
Template Input (Ajax)
var url   = 'hello.tpl';

var data = { name: 'world' };

var func = $.template(url);
// anonymous()

var elem = $.template(url, data);
// [jquery:template]

var html = $.template(url, data, true);
// <p>Hello, <em>world!</em></p>
Data Input

• Object

• Array (of objects)
Data Input (Object)
var str   = '<p>Hello, <em>{%= this.name %}!</em></p>';

var data = { name: 'world' };

var html = $.template(str, data, true);
// <p>Hello, <em>world!</em></p>
Data Input (Array of objects)
var str     = '<p>Hello, <em>{%= this.name %}!</em></p>';

var    data = [
   {   name: 'world' },
   {   name: 'Dolly' },
   {   name: 'mom' }
];

var html = $.template(str, data, true);
// <p>Hello, <em>world!</em></p>
// <p>Hello, <em>Dolly!</em></p>
// <p>Hello, <em>mom!</em></p>
Output

• function

• DOM (as a jQuery instance)

• HTML (as a string)
Output (function)
// This template...
var str = '<p>Hello, <em>{%= this.name %}</em>!</p>';
var func = $.template(str);

// becomes...
function anonymous() {
  var __ = [];
  __.push("<p>Hello, <em>", this.name, "!</em></p>");
  return __.join("");
}

// which can be used as...
var elem = func(data);

// or...
var html = func(data, true);
Output (function)
<p>Hello, <em>
{% if (this.name) { %}
 {%= this.name %}
{% } else { %}
  stranger
{% } %}
!</em></p>

function anonymous() {
  var __ = [];
  __.push("<p>Hello, <em>");
  if (this.name) {
    __.push("", this.name, "");
  } else {
    __.push("stranger");
  }
  __.push("!</em></p>");
  return __.join("");
}
Output (DOM)

DOM output is wrapped in <jquery:template/> to allow
jQuery manipulation and to protect leading and trailing
fragments and elements
<jquery:template>
  <p>Hello, <em>world!</em></p>
  <p>Hello, <em>Dolly!</em></p>
  <p>Hello, <em>mom!</em></p>
</jquery:template>

Hello, <em>world!</em>
// FAIL <em>world!</em>

<em>Goodbye</em>, cruel world!
// FAIL <em>Goodbye</em>
Output (DOM)

Attempted a patch to jQuery to wrap leading and trailing
fragments as text nodes, but then
var elem = $(tpl, obj).appendTo('body').hide();
// FAIL

would require rewrite of all of jQuery's DOM functions :(
Output (DOM)

Still breaks in some instances where markup is too invalid
$.template('<tr><td>{%= this.name %}</td></tr>', data)
  .appendTo('<table/>');

<jquery:template>
  <tr>
    <td>Hello, world!</td>
    <td>Hello, Dolly!</td>
    <td>Hello, mom!</td>
  </tr>
</jquery:template>
<table/>
// FAIL
// Invalid markup squirts out of the target element
Output (HTML)

Fix: use true to render as HTML
var html = $.template('<tr><td>{%= this.name %}</td></tr>',
data, true);

// <tr>
//   <td>Hello, world!</td>
//   <td>Hello, Dolly!</td>
//   <td>Hello, mom!</td>
// </tr>

$('<table/>').append(html);
Known Issues

• Does not properly extract DOM
  text in IE (fix on the way)

• Breaks in some cases where
  markup is invalid
Thanks!

• http://github.com/furf/jquery-template

Contenu connexe

Tendances

Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPaweł Dawczak
 
Oop php 5
Oop php 5Oop php 5
Oop php 5phpubl
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuerySudar Muthu
 
Anko試食会
Anko試食会Anko試食会
Anko試食会susan335
 
8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会Yusuke Ando
 
Introduction to Web Components
Introduction to Web ComponentsIntroduction to Web Components
Introduction to Web ComponentsFelix Arntz
 
Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstartguestfd47e4c7
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Templateguest48224
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Templatemussawir20
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?Radek Benkel
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Componentization css angular
Componentization css angularComponentization css angular
Componentization css angularDavid Amend
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Biglietti, prego! A ticket for the (command) bus
Biglietti, prego! A ticket for the (command) busBiglietti, prego! A ticket for the (command) bus
Biglietti, prego! A ticket for the (command) busFrancesco Face
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal APIAlexandru Badiu
 
7 reasons why developers should love Joomla!
7 reasons why developers should love Joomla!7 reasons why developers should love Joomla!
7 reasons why developers should love Joomla!Bartłomiej Krztuk
 

Tendances (20)

[ HackFest.pl 2012] Testing - what for and how
[ HackFest.pl 2012] Testing - what for and how[ HackFest.pl 2012] Testing - what for and how
[ HackFest.pl 2012] Testing - what for and how
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
Oop php 5
Oop php 5Oop php 5
Oop php 5
 
A Short Introduction To jQuery
A Short Introduction To jQueryA Short Introduction To jQuery
A Short Introduction To jQuery
 
distill
distilldistill
distill
 
Anko試食会
Anko試食会Anko試食会
Anko試食会
 
8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会
 
Introduction to Web Components
Introduction to Web ComponentsIntroduction to Web Components
Introduction to Web Components
 
Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstart
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Componentization css angular
Componentization css angularComponentization css angular
Componentization css angular
 
Convidar para page !!
Convidar para page !!Convidar para page !!
Convidar para page !!
 
Php
PhpPhp
Php
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Biglietti, prego! A ticket for the (command) bus
Biglietti, prego! A ticket for the (command) busBiglietti, prego! A ticket for the (command) bus
Biglietti, prego! A ticket for the (command) bus
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal API
 
7 reasons why developers should love Joomla!
7 reasons why developers should love Joomla!7 reasons why developers should love Joomla!
7 reasons why developers should love Joomla!
 

Similaire à $.Template

Cheap frontend tricks
Cheap frontend tricksCheap frontend tricks
Cheap frontend tricksambiescent
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼Sukjoon Kim
 
C A S Sample Php
C A S Sample PhpC A S Sample Php
C A S Sample PhpJH Lee
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!Guilherme Carreiro
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 
R57shell
R57shellR57shell
R57shellady36
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuerydeimos
 
Maintaining your own branch of Drupal core
Maintaining your own branch of Drupal coreMaintaining your own branch of Drupal core
Maintaining your own branch of Drupal coredrumm
 
Advance Techniques In Php
Advance Techniques In PhpAdvance Techniques In Php
Advance Techniques In PhpKumar S
 

Similaire à $.Template (20)

Cheap frontend tricks
Cheap frontend tricksCheap frontend tricks
Cheap frontend tricks
 
Jquery
JqueryJquery
Jquery
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼
 
Views notwithstanding
Views notwithstandingViews notwithstanding
Views notwithstanding
 
C A S Sample Php
C A S Sample PhpC A S Sample Php
C A S Sample Php
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
R57shell
R57shellR57shell
R57shell
 
Framework
FrameworkFramework
Framework
 
PHP
PHP PHP
PHP
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Maintaining your own branch of Drupal core
Maintaining your own branch of Drupal coreMaintaining your own branch of Drupal core
Maintaining your own branch of Drupal core
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
 
Advance Techniques In Php
Advance Techniques In PhpAdvance Techniques In Php
Advance Techniques In Php
 

Dernier

How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxKaustubhBhavsar6
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIVijayananda Mohire
 
Scenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosScenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosErol GIRAUDY
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kitJamie (Taka) Wang
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveIES VE
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsDianaGray10
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxNeo4j
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox
 
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for  Biomedical ApplicationsGraphene Quantum Dots-Based Composites for  Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applicationsnooralam814309
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameKapil Thakar
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfInfopole1
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 

Dernier (20)

How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptx
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAI
 
Scenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosScenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenarios
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kit
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projects
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
 
Graphene Quantum Dots-Based Composites for Biomedical Applications
Graphene Quantum Dots-Based Composites for  Biomedical ApplicationsGraphene Quantum Dots-Based Composites for  Biomedical Applications
Graphene Quantum Dots-Based Composites for Biomedical Applications
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First Frame
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 

$.Template

  • 2. Why use a template? • Render data as markup • Separation of display logic from business logic • Reusable markup (in theory) • Maybe it’s cleaner? • It’s definitely faster than...
  • 3. The Other Options • String Concatenation • Array.join • DOM Manipulation • jQuery.append
  • 4. String Concatenation var str = ''; str += '<p>Hello, <em>'; str += this.name; str += '</em>!</p>'; body.innerHTML = str;
  • 5. Array.join var arr = []; arr.push('<p>Hello, <em>'); arr.push(this.name); arr.push('</em>!</p>'); body.innerHTML = arr.join('');
  • 6. DOM Manipulation var p = document.createElement('P'); var hello = document.createTextNode('Hello, '); var em = document.createElement('EM'); var world = document.createTextNode(this.name + '!'); em.appendChild(world); p.appendChild(hello); p.appendChild(world); body.appendChild(p);
  • 7. jQuery.append $('<p>').append( 'Hello, ', $('<em>').text(this.name + '!') ).appendTo('body');
  • 8. JavaScript Templating Libraries • mustache.js • HandlebarJS • TrimPath JST • Resig Micro-Templating • jQuery.template
  • 9. $.template • jQuery plugin • Modified Resig Micro- Templating • Allows inline JavaScript • Caching • Ajax • Faster
  • 10. $.template Basics • Converts a string into a function • Caches the rendered function • Function renders data as DOM/ HTML
  • 12. Scope (this) • Rendered template function is executed in the scope of the data object • Dropped with for performance, replaced with this var str = '<p>Hello, <em>{%= this.name %}!</em></p>';
  • 13. Two Types of Tags • Output tags pass their values to the returned output • Functional tags execute arbitrary JavaScript, but do not output any value
  • 14. Output Tags {%= ... %} // Output is added to the output {%= this.property %} // Ternaries can be used for quick conditionals {%= this.property ? this.property : "N/A" %} // JavaScript is executed and added to output {%= (new Date()).getTime() - (this.birthdate).getTime() %}
  • 15. Functional Tags {% ... %} // Value is not added to output {% var pie = 22/7; } // Semi-colons not required, but encouraged for best practice {% var greeting = "Hello, " + this.name } // WIN // Double-quotes are STRICTLY REQUIRED {% var greeting = 'Hello, ' + this.name } // FAIL // Single-quotes allowed in strings {% var greeting = "I'm with " + this.name } // WIN
  • 16. Looping an Array {% for (var i = 0, n = this.images.length; i < n; ++i) { %} {% var img = this.images[i]; } <img src="{%= img.src %}" alt="{%= img.description %}"> {% } %}
  • 17. Conditionals {% if (this.age > 21) { %} <a href="booze.html">Drink up!</a> {% } else { %} <a href="music.html">Enjoy some tunes!</a> {% } %}
  • 18. Subtemplates <h1>{%= this.name %}</h1> {% function renderJob (job) { %} {% var verb = (job.end === "present") ? "work" : "worked"; %} I {%= verb %} at <strong>{%= job.company %}</strong> as a <em>{%= job.position %}</em> {% } %} <ul> {% for (var i = 0, n = this.jobs.length; i < n; ++i) { %} <li>{% renderJob(this.jobs[i]) %}</li> {% } %} </ul>
  • 19. Subtemplates <h1>{%= this.name %}</h1> {% function renderJob (job) { %} {% var verb = (job.end === "present") ? "work" : "worked"; %} I {%= verb %} at <strong>{%= job.company %}</strong> as a <em>{%= job.position %}</em> {% renderDate(job.start, job.end) %} {% function renderDate (start, end) { %} from {%= start %} {%= end === "present" ? "" : "to " + end %}. {% } %} {% } %} <ul> {% for (var i = 0, n = this.jobs.length; i < n; ++i) { %} <li>{% renderJob(this.jobs[i]) %}</li> {% } %} </ul>
  • 20. template + data = output
  • 21. Template Input • string • var • $.ajax (asynchronous) • DOM (via $.fn.template) • Ajax (synchronous)
  • 22. Template Input (string) var str = '<p>Hello, <em>{%= this.name %}!</em></p>'; var data = { name: 'world' }; var func = $.template(str); // anonymous() var elem = $.template(str, data); // [jquery:template] var html = $.template(str, data, true); // <p>Hello, <em>world!</em></p>
  • 23. Template Input (DOM) <script id="tpl" type="text/html"> Hello, {%= this.name %}! </script> var data = { name: 'world' }; var func = $('#tpl').template(); // anonymous() var elem = $('#tpl').template(data); // [jquery:template] var html = $('#tpl').template(data, true); // <p>Hello, <em>world!</em></p>
  • 24. Template Input (Ajax) var url = 'hello.tpl'; var data = { name: 'world' }; var func = $.template(url); // anonymous() var elem = $.template(url, data); // [jquery:template] var html = $.template(url, data, true); // <p>Hello, <em>world!</em></p>
  • 25. Data Input • Object • Array (of objects)
  • 26. Data Input (Object) var str = '<p>Hello, <em>{%= this.name %}!</em></p>'; var data = { name: 'world' }; var html = $.template(str, data, true); // <p>Hello, <em>world!</em></p>
  • 27. Data Input (Array of objects) var str = '<p>Hello, <em>{%= this.name %}!</em></p>'; var data = [ { name: 'world' }, { name: 'Dolly' }, { name: 'mom' } ]; var html = $.template(str, data, true); // <p>Hello, <em>world!</em></p> // <p>Hello, <em>Dolly!</em></p> // <p>Hello, <em>mom!</em></p>
  • 28. Output • function • DOM (as a jQuery instance) • HTML (as a string)
  • 29. Output (function) // This template... var str = '<p>Hello, <em>{%= this.name %}</em>!</p>'; var func = $.template(str); // becomes... function anonymous() { var __ = []; __.push("<p>Hello, <em>", this.name, "!</em></p>"); return __.join(""); } // which can be used as... var elem = func(data); // or... var html = func(data, true);
  • 30. Output (function) <p>Hello, <em> {% if (this.name) { %} {%= this.name %} {% } else { %} stranger {% } %} !</em></p> function anonymous() { var __ = []; __.push("<p>Hello, <em>"); if (this.name) { __.push("", this.name, ""); } else { __.push("stranger"); } __.push("!</em></p>"); return __.join(""); }
  • 31. Output (DOM) DOM output is wrapped in <jquery:template/> to allow jQuery manipulation and to protect leading and trailing fragments and elements <jquery:template> <p>Hello, <em>world!</em></p> <p>Hello, <em>Dolly!</em></p> <p>Hello, <em>mom!</em></p> </jquery:template> Hello, <em>world!</em> // FAIL <em>world!</em> <em>Goodbye</em>, cruel world! // FAIL <em>Goodbye</em>
  • 32. Output (DOM) Attempted a patch to jQuery to wrap leading and trailing fragments as text nodes, but then var elem = $(tpl, obj).appendTo('body').hide(); // FAIL would require rewrite of all of jQuery's DOM functions :(
  • 33. Output (DOM) Still breaks in some instances where markup is too invalid $.template('<tr><td>{%= this.name %}</td></tr>', data) .appendTo('<table/>'); <jquery:template> <tr> <td>Hello, world!</td> <td>Hello, Dolly!</td> <td>Hello, mom!</td> </tr> </jquery:template> <table/> // FAIL // Invalid markup squirts out of the target element
  • 34. Output (HTML) Fix: use true to render as HTML var html = $.template('<tr><td>{%= this.name %}</td></tr>', data, true); // <tr> // <td>Hello, world!</td> // <td>Hello, Dolly!</td> // <td>Hello, mom!</td> // </tr> $('<table/>').append(html);
  • 35. Known Issues • Does not properly extract DOM text in IE (fix on the way) • Breaks in some cases where markup is invalid

Notes de l'éditeur