jQuery DNA Template
Incredibly simple and yet powerful non-destructive javascript templating system. Allows you to effortlessly build and efficiently manage UI code (or let web designers to do that without breaking your UI-building javascript code).
Table of Contents
Features
- Supports nested templates with for-each-like behavior (recursive templates supported)
- You can apply template multiple times to the same element to update UI with changed values
- Support for adding/removing classes conditionaly (e.g. add this class if value is true )
- Support for conditional attributes (e.g. check the check-box if value is true)
- Support for conditional hidding/showing/removal of elements based on values
- Super lightweight with only 2.5kB of compressed Javascript
- And more...
Quick Introduction
First you need to include one Javascript and CSS file provided you already use jQuery on your page.
Example: Replace … with the real path pointing to your files.
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="…/template.css"/>
<script src="…/jquery.template.min.js"></script>
</head>
<body>
</body>
</html>Now you can add the z-var="PROPERTY TARGET" attribute to any element
and then call $(element).template(...) on that element or any parent.
The z-var attribute holds (comma-separated) instruction(s)
specifying what should be replaced and where or what should be done.
The TARGET is usually . (dot) to insert the value as text in the
element or @ATTR_NAME to insert variable into attribute. It is
simple and you will understand it in a minute by looking at examples
bellow or by jumping to the syntax section.
Let's see how it works in real world.
Assume that all examples in this section use this Javascript to apply
the template. We pass quite complex data object to the template. The
values in the object will be inserted in various points defined by
z-var in HTML as you will see bellow.
$('.target').template({
'name': 'John Smith',
'validated': true,
'list': ['aa', 'bb'],
'listExt': [
{'first': 'John', 'last': 'Doe', 'validated': true},
{'first': 'Jane', 'last': 'Smith', 'validated': false}
],
'propObj': {
'first': 'Baby',
'last': 'Doe'
}
});Now the examples that we apply the code to.
Example:
<div class="target" z-var="name ., validated .lock-icon"></div>
<input class="target" type="checkbox" z-var="validated @checked"/><label>Checked</label>Result:
<div class="target lock-icon" z-var="name ., validated .lock-icon">John Smith</div>
<input class="target" type="checkbox" z-var="validated @checked" checked="checked"/><label>Checked</label>Explanation:
- "
name ." - add valuenameas the text value - "
validated .lock-icon" - add classlock-iconifvalidatedis true - "
validated @checked" - addchecked="checked"attribute if true
Example:
<div class="target" z-var="validated ?">Validated</div>
<div class="target" z-var="!validated ?">Not Validated</div>
<div class="target" z-var="!validated !">Insecure</div>Result:
<div class="target" z-var="validated ?">Validated</div>
<div class="target" z-var="!validated ?" style="display: none;">Not Validated</div>Explanation:
- "
validated ?" - show element ifvalidatedis true, hide otherwise - "
!validated ?" - the oposite of above - hide if true, show if false - "
!validated !" - remove (destructive) the element ifvalidatedis false
Example:
<div class="target" z-var="name .">My name is ${name}</div>Result:
<div class="target" z-var="name .">My name is John Smith</div>Explanation:
- "
name ." - add value ofnamein place of${name}placeholder
Example:
<ul class="target">
<li template="[list]" z-var="value ."></li>
</ul>Result:
<ul class="target">
<li z-var="value ." class="template-clone" template-clone="[list]">aa</li>
<li z-var="value ." class="template-clone" template-clone="[list]">bb</li>
<li template="[list]" z-var="value ."></li><!-- invisible -->
</ul>Explanation:
Duplicate the element with template="[list]" attribute for each value inside list array and
value .insert the array value as plain text into the element- All elements with an attribute
templateare automatically hidden bytemplate.cssyou've included on the page (see above)
Example:
<ul class="target">
<li template="[listExt]" z-var="first ., last ., last @title">${first} ${last}</li>
</ul>Result:
<ul class="target">
<li z-var="first ., last ., last @title" class="template-clone" template-clone="[listExt]" title="Doe">John Doe</li>
<li z-var="first ., last ., last @title" class="template-clone" template-clone="[listExt]" title="Smith">Jane Smith</li>
<li template="[listExt]" z-var="first ., last ., last @title">${first} ${last}</li><!-- invisible -->
</ul>Explanation:
Duplicate the element with template="[listExt]" attribute for each
value inside listExt array and use respective value object to insert
variables into duplicated element as follows
- "
first ., last ." - add first and last name as text in positions indicated by${PROP_NAME}placeolders - "
last @title" - add last name intotitleattribute
Example:
<ul class="target">
<li template="{listExt}" z-var="first ., last .">${first} ${last}</li>
</ul>Result:
<ul class="target">
<li z-var="first ., last ., last @title" class="template-clone" template-clone="[listExt]" title="Doe">Baby Doe</li>
<li template="{listExt}" z-var="first ., last .">${first} ${last}</li><!-- invisible -->
</ul>Explanation:
Duplicate the element with template="{propObj}" and use propObj
to apply templates recursively to cloned element. It behaves as if you called
$('*[template="{propObj}"]').template(data.propObj, true);
- "
first ., last ." - add first and last name as text in positions indicated by${PROP_NAME}placeolders - "
last @title" - add last name intotitleattribute
Interactive Examples
The best example is the one you can play with.
- Basic example - insert variable into attribute and text
- Simple list example - iterate through the array and generate list
- Simple Paging - simple list with paging
- Mixed list example - simple variables with nested array to generate list
- Form example - toggle check-boxes, set values on select-boxes, change button labels and classes...
- UI Updates - example of continuous live UI updates
Syntax
Javacript
$(SELECTOR).template(DATASET [, IN_PLACE]);DATASET- Object or Array of Objects or Object with nested Arrays or Objects with properties and their values to be used when resolvingz-varattributes.IN_PLACE- boolean value.true: don't clone the element prior to replacing variables,false: clone the element,undefined: clone if element has the attributetemplateotherwise replace vars in-place without cloning.
HTML
<element z-var="[!]DATASET_PROPERTY (TARGET|ACTION)[, ...]">...</element>DATASET_PROPERTY- property name on the object passed to$(selector).template(DATASET)method.TARGET- use following notation.- to insert value as TextNode,@ATTR_NAMEto insert value into attribute (Note: IfDATASET_PROPERTYsitruethen attribute's value will be same as attribute's name, e.g.checked="checked"forz-var="isChecked @checked"ifisChecked = true.)+- load serialized HTML text in variable as child HTML,=- set variable's value as form field's value. If the field is a check-box or radio-box then (un)check it if value is boolean otherwise check it only if value equals to input'svalueattribute.
ACTION- following actions are available?- hide element if value is false,!- remove element if value is false (note: this is destructive action - you cannot re-apply new dataset again with the same effect),.CLASS_NAME- add/remove class if value is true/false.
!- "not" - negates theDATASET_PROPERTYvalue for the purpose of evaluation whatACTIONshould be taken.
To determine if ACTION should be taken DATASET_PROPERTY is converted into boolean true or false. Following values are considered false:
- an empty
Array - an empty
Object - number
0 - string representing numeric value zero (e.g.
"0.00") - boolean
false null- empty string
If you try to insert the plain Array object as text or value then its length gets inserted instead. You can use it to insert item counts.
<element template="(NAME|[PROPERTY]|{PROPERTY})">...</element>NAME- any name of your choice. All elements having attributetemplateare hidden by default (make sure to include thetemplate.css). Applying template to such element will clone it, remove thetemplateattribute and then apply the dataset. See Simple list example.[PROPERTY]- name of the property onDATASETobject that holds nested Array or Object to be automatically applied to this template. See Mixed list example.{PROPERTY}- name of the property that contains an object. Take this object and apply variables into it to this element.
<element template-scope>...</element>template-scope- protect children of an element with attributetemplate-scopefrom being modified by template applied to such element's ancestor. DNA Template will ignore anyz-varattributes on elements inside element withtemplate-scopeattribute.
More
For more advanced examples and explanations see file
tutorial/index.html or just drop me a message what part
is unclear and I will update this documentation...