donut_small Tiny Templates JS 
Blog posts

Tiny Templates JS

A tiny reactive template engine written in javascript.

Download: tiny-templates-0.7.js | tiny-templates-0.7.min.js

Overview

TinyTemplates is a tiny templating engine in javascript that lets you create reusable, reactive components that can be rendered and updated in the DOM. The templates are created by using a view that consists of the standard the HTML syntax combined with a few additional nodes that work as statements (if) or loops (for, foreach). Data, that needs to be reactive, is stored as state that embeds in the view to get updated if any changes are made to the data. diffDOM is used to detect and patch these changes in as few steps as possible. Please have a look at the example below for a better understanding of the syntax.

Example


// Our example is a simple counter.
let counter = new TinyTemplate(
  // Name
  "counter",
  // State
  {
    number: 0
  },
  // Methods
  {
    increaseNumber: function() {
      this.changeState({ number: this.getState("number") + 1 });
    },
    reset: function() {
      this.changeState({ number: 0 });
    }
  },
  // Template-view
  `<div class="counter>
      <fieldset>
        <legend><b>Counter</b></legend>
        <p>Counting: {{number}}</p>
        <button on-event="onclick" call="increaseNumber">Increment</button>
        <button on-event="onclick" call="reset">Reset</button>
        </fieldset>
     </div>`
);

// Mount the template to a root node to add it to the DOM.
counter.mount(document.getElementById("root-node-id"));

  let a = 20;
  while(a>0){
    console.log(a); // Print.
    ++a;
  }