/g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();"> /g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Micro Templates for Javascript Norman White. Background Separate HTML code from data Provide a flexible reusable template to generate html with embedded.

Similar presentations


Presentation on theme: "Micro Templates for Javascript Norman White. Background Separate HTML code from data Provide a flexible reusable template to generate html with embedded."— Presentation transcript:

1 Micro Templates for Javascript Norman White

2 Background Separate HTML code from data Provide a flexible reusable template to generate html with embedded data Reduce the amount of code that needs to be written Provide ability to develop standard templates for web applications Original article – http://ejohn.org/blog/javascript-micro-templating/

3 Original MicroTemplate // Simple JavaScript Templating // John Resig - http://ejohn.org/ - MIT Licensed (function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str.replace(/[\r\t\n]/g, " ").split(" )[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();

4 Tricks that allow micro templates “Hide” the template definition in a script type that the browsers don’t recognize, then call the micro template function to dynamically fill in the data elements. Use Javascript’s powerful regular expression facilities to create a tiny templating expansion function that is passed a template and data, and generates an html string that can then be used somewhere. You can precompile the templating function for performance.

5 Example Template " class=" "> "/> "> : <script><div><div> <a

6 Example Template " class=" "> "/> "> : <script><div><div> <a NAME

7 Example Template " class=" "> "/> "> : <script><div><div> <a Data Element

8 Usage var results = document.getElementById("results"); results.innerHTML = tmpl("item_tmpl", dataObject); QUESTION: What is in “dataObject” ?

9 Many micro templates now Jquery Templates Mustache Pure Mootools Whiskers …

10 Mustache Popular micro template Used in Dreamweaver examples “Logic-less” – No if, else, for, … 300 lines of Javascript code Works in python, ruby or javascript – Can run on server side or browser

11 Typical Template Hello {{name}} You have just won ${{value}}! {{#in_ca}} Well, ${{taxed_value}}, after taxes. {{/in_ca}}

12 Data Object { "name": "Chris", "value": 10000, "taxed_value": 10000 - (10000 * 0.4), "in_ca": true }

13 Result Hello Chris You have just won $10000! Well, $6000.0, after taxes.

14 Usage Mustache only uses “tags”, no logic Tag Types Variables {{name}} {{{name}}} (unescape html) Sections – renders blocks of text one or more times {{#person}} …. {{/person}} Lambdas – Callable objects, i.e. functions

15 Some Mustache Examples Template {{name}} {{age}} {{company}} {{{company}}} Hash (input data) { “name”: “Chris”, “company”: “ GitHub ” { Output Chris <b>GitHub</b> GitHub

16 Lists (Note automatic iteration) Template: – {{#repo}} – {{name}} – {{/repo}} Hash: { "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" }, ] } Output: resque hub rip

17 Lambdas Template: – {{#wrapped}} – {{name}} is awesome. – {{/wrapped}} Hash: – { – "name": "Willy", – "wrapped": function() { – return function(text) { – return " " + render(text) + " " } – } Output: – Willy is awesome.

18 Invoking Mustache Just call Mustache.render(template, data) Include mustache.js var view = { title: "Joe", calc: function () { return 2 + 4; } }; var output = Mustache.render("{{title}} spends {{calc}}", view); Output = “Joe spends 6”

19 Typical Uses Get data from server as a JSON string Decode JSON data and pass to a mustache template to display. Many examples of Mustache on-line


Download ppt "Micro Templates for Javascript Norman White. Background Separate HTML code from data Provide a flexible reusable template to generate html with embedded."

Similar presentations


Ads by Google