Subscribe to RSS Feed

There is still lack of documentation for Domplate (even if there are already some articles) and so, I have decided to put together set of how to examples. I believe that this kind of simple and focused examples is good start for everybody who wants to understand how Domplate works and use it for building HTML UI.

Each example consists usually from following parts:

  • Domplate Script: the script used to describe Domplate template
  • Input Data (object): input data for a dynamic template
  • CSS: set of CSS rules used by result DOM

Every example also contains a brief description and a Demo button that can be used to run the example with Domplate Runner and see/explore generated markup. Since the runner is based on Domplate, specifically on
JQuery Domplate Plugin (made by Christoph Dorn) and Domplate doesn't support other browsers yet, it runs only in Firefox. So, if you are not using Firefox, perhaps it's good time to install it now. ;-)

Hello World!

The very first example shows basic steps you need to do to define and execute a template.

var template = domplate(
{
    tag:
        DIV("Hello World!"),
});

template.tag.replace({}, parentNode, template);

Notice that the template is created with domplate function and contains one
tag definition. The tag consists from one DIV constructor (a function).
In order to execute the template, the example uses a replace method
(there are other methods yet) and passes an input object (empty in this case), parent DOM node (where the result should be inserted) and scope object (the template itself) into it.

How to use input data

This example shows how an input object can be used to provide dynamic data for a template.

var inputObject = {
    firstName: "Jan",
    lastName: "Odvarko"
};
var template = domplate(
{
    tag:
        DIV(
            SPAN("First Name: "),
            SPAN("$object.firstName"),
            BR(),
            SPAN("Last Name: "),
            SPAN("$object.lastName")
        )
});

template.tag.replace({object: inputObject}, parentNode, template);

The template refers to a property of the input object using a "$" character at the beginning of the property name. Standard dot notation is used to access inner properties. The actual value from the object is used when the template is executed.

How to construct a FOR Loop

This example shows how to use FOR loop and iterate array of input objects.

var inputArray = ["red", "green", "blue", "white"];
var template = domplate(
{
    tag:
        FOR("item", "$array",
           DIV("$item")
        )
});

template.tag.replace({array: inputArray}, parentNode, template);

A loop is constructed using a FOR constructor, which expects two parameters. The first defines a variable, which contains the actual value from the array in each cycle and the second is an array to be iterated.

How to handle a DOM event

This example shows how to register an event handler.

var inputArray = ["red", "green", "blue", "white"];
var template = domplate(
{
    tag:
        FOR("item", "$array",
            DIV({onclick: "$handleClick"},

               "$item"
            )
        ),

    handleClick: function(event)
    {

        alert(event.target.innerHTML);
    }
});

template.tag.replace({array: inputArray}, parentNode, template);

The template registers a handler for every generated DIV element and shows
alert box with content of the clicked element. Notice that the scope object
(which is usually the template itself) is used to execute the handleClick function.

If the constructor's attribute name begins with "on" it's treated as an
event name (without "on") for corresponded DOM event. It's value must be a always a function that is registered as the event listener.

How to generate DOM attributes

This example shows how to generate HTML attributes.

.green {
    color:green;
}
var inputObject = {
    label: "Click Me!",
};
var template = domplate(
{
    tag:
       BUTTON({class: "green",
              checked: "true",
              type: "checkbox",
              onclick: "$onButtonClick"},
           "$object.label"
        ),

    onButtonClick: function(event)
    {
        alert("Hello World!");
    }
});

template.tag.replace({object: inputObject}, parentNode, template);

Attributes are defined as members of an object that is passed as the first
parameter to the BUTTON constructor.

How to reuse an existing template

This example shows how to use TAG constructor in order to reuse an existing template.

var template = domplate(
{
    tag:
        DIV(
            TAG("$anotherTag")
        ),

    anotherTag:
        SPAN("Embedded Tag"),
});

template.tag.replace({}, parentNode, template);

An existing tag can be simply referenced through a TAG constructor.

How to pass data into aggregated template

See another example of tag reusing that also shows how to pass data into
embedded template.

var inputArray = ["Honza", "Radek", "John", "Mike"];
var template = domplate(
{
    table:
        TABLE({border: "1", width: "100px"},
            FOR("item", "array",
                TAG("$row", {name: "$item"})
            )
        ),

    row:
        TR({align: "center"},
            TD("$name")
        )
});

template.table.replace({array: inputArray}, parentNode, template);

You can see that input object is passed into the embedded TAG as a second parameter.

How to set DOM properties

This example shows how to set a new property on generated DOM object.

var cars = [
  {name: "Honda Pilot", price: " $36,820 - $49,920"},
  {name: "Chevrolet Aveo", price: "$13,270 - $15,770"},
  {name: "Toyota Corolla", price: " $14,835 - $23,480"}
];
var template = domplate(
{
    tag:
        FOR("item", "array",
            DIV({_myprop: "$item", onclick: "$onClick"},
                "$item.name"
            )
        ),

    onClick: function(event)
    {
        var car = event.target.myprop;
        alert(car.price);
    }
});

template.tag.replace({array: cars}, parentNode, template);

If the constructor's attribute name begins with "_" it's always treated
as a DOM property. Notice that the name of created property is without "_".

Constructor attribute naming rules

As you could notice from the previous examples there are some rules for constructor attribute name. See the following list with all existing rules:

  1. Name begins with "on": value of this attribute must be a function, which is used as an event handler for specified event
  2. Name begins with "_": a new property is created on this DOM element ("_" isn't part of the result property name) with appropriate value
  3. Name begins with "$": if actual value of the attribute is true (boolean) a new class with the same name (without "$") is inserted into the class attribute of the DOM element.

Rss Commenti

11 Comments

  1. It would be cool if minefield nightlies would not be discriminated by the browser sniffing, which indicates some sort of homegrown browser sniffing.

    #1 Bernd
  2. Hi Bernd,
    I am not sure if I understand the comment. What do you mean by homegrown browser sniffing? Is there anything I could improve?
    Honza

    #2 Honza
  3. The example works on Gecko.
    It includes SeaMonkey, Epiphany, Galeon, K-meleon, Camino and others.

    http://developer.mozilla.org/en/Browser_Detection_and_Cross_Browser_Support

    navigator.product == 'Gecko'

    should work.

    #3 Asrail
  4. Hi Asrail, thanks for the tip! The browser detection is now based on searching "Gecko/" string within the navigator.userAgent (PHP).
    Any suggestion for better solution is appreciate. I am PHP rookie only ;-)

    #4 Honza
  5. Thanks Honza.
    Now I can use the demos.

    Most non-gecko browser which are compatible use "(like Gecko)", so this test is fine..
    It works as expected for each gecko or non-gecko based browsers I have around on Linux. It will also work fine for IE and I think it will work for Safari.
    So it works very well now.

    Nice post.

    #5 Asrail
  6. FYI - Safari still not passing the sniffing. Maybe change the matching string just to "Gecko". (It is sending "(like Gecko)" as part of it's user agent string.)

    #6 Jakub
  7. Jakub... it is not guaranted to work on Safari, so its removal was intentional.

    The creator of the plugin said that. So Safari is not supported.

    If you do some change to your user agent and notice that Safari passes, you could contact him and tell it.
    The link for his blog is on the "JQuery Domplate Plugin" link on the post.

    #7 Asrail
  8. Very cool demonstration and tutorial, Jan. Thanks for this.

    #8 robcee
  9. Great work on the Domplate Runner! The examples are also very useful.

    #9 Christoph Dorn
  10. Doesn't work in Opera 10.53 at all. :( Cant use for anything,

    #10 Witek
  11. @Witek: Could you please test if HAR Viewer (based on a new version of Domplate) works for you? http://www.softwareishard.com/har/viewer/
    Honza

    #11 Honza

Sorry, the comment form is closed at this time.