Mucilage – lightweight data/template binding

Information

Mucilage is a lightweight data to template binding engine which allows to bind the updating of the template with the data. Mucilage return an object containing methods matching the data keys which can then be used to update the data object or retrieve current values.

Due to the nature of the template engine the template is re-compiled everytime the data object changes.

Mucilage also come in a “light build” which is based on a strip down version of the template engine so it allows only interpolation and doesn’t have any configurable settings.

Usage

Basic

This can be done with the light version as only interpolations.

var template = '<h1>{{=$.title}}</h1><p>{{=$.message}}</p>',
    data = {
    title: 'Title',
    message: 'Message'
    },
    muc = mucilage(template, data, document.getElementById('content')); 

    // the content element now contains <h1>Title</h1><p>Message</p>

    // this will update the Message in 3 seconds
    setTimeout(function() {
    console.log(muc.message());
    muc.message('New message');
    console.log(muc.message());
    }, 3000);

Advanced usage

Requires the full version

<div id="content"></div>
<script type="text/mucilage-template" id="templ">
<h1>Just static text</h1>
<p>Interpolation {{=$.f1   +    $.f3}} </p>
<div> JavaScript block evaluation
{{ for(var i=0; i < $.f2; i++) {
    console.log("Pass\t" + i);
    }}
    <div>{{=$.f3}}</div>
    {{ } }}
    </div>
    <div> Encoding {{!'<a   href="http://github.com"></a>'}}</div>
</script>
// original data and template
var data = {
    f1: 10,
    f2: 10,
    f3: 10,
    },
    template = document.getElementById('templ').text;

// convert data into a mucilage object
data = mucilage(template, data, document.getElementById('content'));

// update data object and update the template
setTimeout(function(){
    data.f1(5);
}, 3000);

Get it

Full feature version is around 4KB and the light version is around 1.2KB.

Available from github at https://github.com/gillescochez/mucilage see test for various usage cases.

This entry was posted in Plugins & engines. Bookmark the permalink.

Comments are closed.