Templates
class: center, middle .title[ Front-end training # JS Template Engines ] --- # Templates A web template system uses a template processor to combine web templates to form finished web pages, possibly using some data source to customize the pages or present a large amount of content on similar-looking pages. _(c) Wikipedia_ In practice templates are very useful since allows you to define dynamically changeable parts of HTML in human-readable format. --- # Template syntax Usually templates are just an html-like parts of code with custom tags syntax. To use values you need to specify _template context_. To use template in your page you need two things: a _template engine_ and _template_ itself. Template engine process given template string and values passed and produce ready-to-use HTML. For example template might look like: ```
{{ for i in :values }}
{{ =i }}
{{ /for }}
``` And this string may be processed like: ``` templateEngine.compile(templateString, { values: [1, 2, 3] }); // -> //
1
2
3
``` --- # Common template features - Interpolation (replace some placeholder with assigned value) - Evaluation (evaluate expression inside tag) - Conditionals (render part of template according to passed values) - Looping (repeatedly render some part of code) - Blocks/partials/inheritance (mark some block as 'changeable' and redefine it in 'child' templates) - Mixins (create some reusable elements inside a template) - Possibility to change syntax - Useful features: autorendering to element, template loading, etc --- # Microtemplates overview Originated at [John Resig's post about microtemplates](http://ejohn.org/blog/javascript-micro-templating/) microtemplates now are one of the most used template engines. Microtemplates called 'micro' because of their size (original implementation is 35 lines long, including comments and formatting). Features often are sacrificed in order to get lightweight template engine. In wild most commonly used microtemplate engine is '_.template' (underscore template), which is an modified version of original microtemplates, but adding some features (mainly - added posibility to change syntax). Microtemplates use javascript for evaluation syntax. --- # Microtemplates features Features available - Interpolation (`<%= variable %>`) - Evaluation (`<% /* any code here */ %>`) - Repeating (js-syntax) - Conditionals (js-syntax) - Configurable syntax (You may change `<%` and `%>`) Not available - Blocks/mixins/inheritance --- # Using microtemplates [Home page](http://underscorejs.org/#template) Microtemplates need to be compiled _before_ usage. They are compiled into a function, which (when called) produce output based on given input ``` // template.mtpl
<% for (var i = 0; i < items.length; i++) { %> <% if (i % 2 == 0) %>
<%= items[i] %>
<% } %>
``` ... ``` // in our application, after we load content of template.mtpl to 'templateString' var compiledTemplate = _.template(templateString); var readyHtml = compiledTemplate({ values: [0, 1, 2, 3, 4, 5, 6, 7, 8] }); // produce string document.body.innerHTML = readyHtml; ``` --- # Mustache [Home page](http://mustache.github.io/mustache.5.html) Mustache is a 'logic-less' templates. Main feature - mustache templates available for all languages, so same templates may be used both client and server side. Mustache use `{{ val }}` syntax by default. --- # Mustache features available - Interpolation `{{ value }}` - Sections `{{#value}} ... {{/value}}` - If `value` is empty list/falsy value - section is not rendered - If `value` is list - section rendered for every value in list - If `value` is not-falsy value - it is used as context for section (e.g. `{ value: { "one" } }`) - Inverted sections `{{^ value}} ... {{ /value }}` - Lambdas - if `value` is a function pass section and context to this function. - Comments `{{! comment }}` - Partials '{{> part }}' - Configurable syntax Not available - Logic (variable assigment, usual loops and conditionals) --- # Mustache sample [Based on this mustache implementation](https://github.com/janl/mustache.js/) ``` // user.mustache
Name: {{name}}
, {{#surname}} Surname: {{surname}} {{/surname}} {{^surname}}
No surname specified
{{/surname}}
``` ``` // app.mustache
List of users
{{#users}} {{> user }} {{/users}}
``` ``` $('target').innerHTML = Mustache.render($tpl('main'), users, { user: $tpl('user') }); ``` --- # Jade [Home page](http://jade-lang.org) Jade is a terse language for writing HTML templates. - Produces HTML - Supports dynamic code - Supports reusability (DRY) Jade use own whitespace-based syntax. Originally developed to use with nodejs Jade templates can be used on client side, but requires compilation. --- # Jade features - Interpolation (`=var`) - Inline javascript code - Conditionals - Extends - Mixins - Includes - Inheritance - Iteration Not available - Changing syntax --- # Jade sample _use `clientjade` to produce templates for browser_ ``` // user.jade mixin user(val) li span Name: #{val.name}, if val.surname span Surname: #{val.surname} else i No surname specified ``` ``` // main.jade include ./user h1 List of users for u in users +user(u) ``` ``` jade.render($('target'), 'main', users); ``` --- # Other engines There are a lot of other template syntaxes (noticeably ERB). Simplest templates ever :) : ``` function template(str, val) { return str.replace(/{{\w+}}/g, function(match) { return val[match.replace(/^{{|}}$/g, '')] || match; }); } template('
{{greet}}
', { greet: 'Hello' }); // ->
Hello
``` [Template chooser](http://garann.github.io/template-chooser/) will help you detect which template engine is for you