RepositoryJavaScriptDEĐức
nextapps-de

nextapps-de/mikado

The fastest template library/engine for building web-based user interfaces and apps.

853sao
38fork
5issue
2lượt xem

Thành tựu nổi bật

Những danh hiệu mới nhất của dự án

1
TINIX TRENDING·Chủ đề: template-library

#1 Repository của tuần

1
TINIX TRENDING·Chủ đề: virtual-dom

#1 Repository của tuần

1
TINIX TRENDING·Chủ đề: mustache-templates

#1 Repository của tuần

Mikado - Webs fastest templating engine

Mikado is the webs fastest template engine for building user interfaces. Carefully crafted to get the most out of the browser. Also providing the fastest Express Render Engine of today. Super-lightweight, outstanding performance, no dependencies.

Getting Started  •  Options  •  API  •  Benchmark  •  Template Compiler  •  Server-Side-Rendering  •  Express Render Engine  •  Reactive  •  Hydration  •  Web Components (Shadow DOM)  •  Changelog

When you are coming from any previous version: Migration Guide 0.8.x

Benchmark:

Demo:

Support this Project

Mikado was getting so much positive feedback and also feature requests. Help keeping Mikado active by a personal donation.

Donate using Open Collective Donate using Github Sponsors Donate using Liberapay Donate using Patreon Donate using Bountysource Donate using PayPal

Table of contents

Get Latest

Do not use the "src" folder of this repo. It isn't meant to be used directly, instead it needs compilation. You can easily perform a custom build, but don't use the source folder for production. You will need at least any kind of compiler which resolve the compiler flags within the code. The "dist" folder is containing every version which you probably need including unminified modules.

BuildFileCDN
mikado.bundle.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.debug.js
mikado.bundle.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.min.js
mikado.bundle.module.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.module.debug.js
mikado.bundle.module.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.bundle.module.min.js
mikado.es5.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.es5.debug.js
mikado.es5.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.es5.min.js
mikado.light.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.debug.js
mikado.light.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.min.js
mikado.light.module.debug.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.module.debug.js
mikado.light.module.min.jsDownloadhttps://rawcdn.githack.com/nextapps-de/mikado/0.8.4/dist/mikado.light.module.min.js
Javascript ModulesDownloadhttps://github.com/nextapps-de/mikado/tree/0.8.4/dist/module
Javascript Modules (Minified)Downloadhttps://github.com/nextapps-de/mikado/tree/0.8.4/dist/module-min
Javascript Modules (Debug)Downloadhttps://github.com/nextapps-de/mikado/tree/0.8.4/dist/module-debug
mikado.custom.jsRead more about "Custom Build"

All debug versions are providing debug information through the console and gives you helpful advices on certain situations.

Bundles

Bundles export all their features as static functions to the public class namespace "Mikado" e.g. Mikado.register().

The abbreviations used at the end of the filenames indicates:

  • bundle All features included, Mikado is available on window.Mikado
  • light Only basic features are included, Mikado is available on window.Mikado
  • es5 bundle has support for EcmaScript5, Mikado is available on window.Mikado
  • module bundle is a Javascript module, Mikado is available by import Mikado from "./mikado.bundle.module.min.js"
  • min bundle is minified
  • debug bundle has enabled debug mode (only for development purposes, do not use for production)

Module

When using modules you can choose from 2 variants: mikado.xxx.module.min.js has all features bundled on the public class namespace e.g. Mikado.register(), whereas the folder /dist/module/ export most of the features as functions which needs to be imported explicitly by import { register } from "./dist/module/mikado.js".

Also, for each variant there exist:

  1. A debug version for the development
  2. A pre-compiled minified version for production

Browser

Load the bundle by a script tag:



NPM

Install Mikado via NPM:

npm install mikado

The dist folder are located in node_modules/mikado/dist/.

Javascript Modules

Use the bundled version exported as a module:

Also, pre-compiled non-bundled production-ready modules are located in dist/module-min/.

You can also load modules via CDN:

Loading modules via CDN commonly expects to build/bundle your app properly before distribution. Do not load them via CDN in production.

Feature Comparison "Bundle vs. Light"

Featuremikado.bundle.jsmikado.light.js
Template Render Engine ✓✓
DOM State Caching ✓✓
Shared Pools / Live Pools ✓✓
Keyed Recycle ✓✓
Non-keyed Recycle ✓✓
Reconcile (Diffing) ✓✓
Hydration ✓✓
Template Expressions ✓✓
Conditional Template Structures ✓✓
Includes/Partials/Loops ✓✓
Shadow DOM ✓✓
Web Components ✓-
Runtime Compiler ✓-
Event Delegation + Routes ✓-
Reactive (Proxy, Observer) ✓-
Asynchronous Render ✓-
View Manipulation Helpers ✓-
DOM Cache Helpers ✓-
File Size (gzip)9.3 kb3.7 kb

Benchmark Ranking (Rendering Performance)

Run the benchmark (non-keyed recycle):
https://raw.githack.com/nextapps-de/mikado/bench/

Run the benchmark (keyed recycle):
https://raw.githack.com/nextapps-de/mikado/bench/#keyed

Run the benchmark (internal/data-driven):
https://raw.githack.com/nextapps-de/mikado/bench/#internal

The values represent operations per second, each benchmark task has to process a data array of 100 items. Higher values are better, except for memory (the sum of allocated memory during the whole test).

Keyed Test Results

LibraryRAMCreateReplaceUpdateOrderRepaintAddRemoveToggleClearScoreIndex
mikado553589278019981613426253605293062930589215151219320292
solid442438223020362131013443645952489178587082531237
inferno462551215114722139001679647802072777245417623834
mithril451672150515406138681663835992110956534152522328
stage056203024461121397491103344271808372099043419935
redom81151714211024296141087028571606248752807516022
domc1243600342434373472351235926670454010030212038
innerhtml672791267624712823279929435752390110340510535
surplus9229692577228123862379228541973023869169132
doohtml7123972308220822082229227542852945631628229
sinuous15120382112245424592461250648203276595568125
jquery10321951919189320922093208439032594192206621
lit-html19914101329134913511333139324151764208374615
ractive187073967269068669172512479177394227
knockout10813992892912912803555244293424124

The index is a statistic rank having a maximum possible value of 100, this requires a library to be the best in each test category (regardless how much better). The score value is based on median factorization, here a score of 100 represents the statistical midfield.

API Overview

Most of these methods are optional, you can just use view.render(data) to apply all changes automatically.

Constructor:

Instance properties:

Static properties (not included in mikado.light.js):

Static methods:

Static methods (not included in mikado.light.js):

Instance methods:

Instance methods (not included in mikado.light.js):

View manipulation helpers (optional, not included in mikado.light.js):

Static DOM Cache helpers (optional, not included in mikado.light.js):

Observable constructor (optional, not included in mikado.light.js):

Observable array-like methods (optional, not included in mikado.light.js):

Mikado Options

Each Mikado instance, also named includes/partials can have their own options. Except inline partials always inherits the same options from its parent. For this reason you should prefer named includes over inlining in certain situations.

OptionDescriptionDefault
root
mount
The destination root element on where the template should be rendered.null
templateYou will need to assign a template to the Mikado instance (or the name of the template when already registered/loaded).
asyncPerform the .render(data) task asynchronously and return a Promise.false
cacheEnable/disable DOM state caching which can greatly increase performance by a factor up to 25. When enabled make sure to use the DOM Cache Helpers when manipulating the DOM directly on properties which are also covered by template expressions.false
observeWhen using Mikado.Array() for reactive approach you will need to pass this array instance to this property.null
recycleWhen enabled all dom elements which are already rendered will be re-used (recycled) for the next render task. This performs better, but it may produce issues when manual dom manipulations was made which are not fully covered by the template. Alternatively use the keyed strategy, which limits recycling of components by matching the same data key (e.g. ID).false
statePass an extern object which should be referenced as the state used within template expressions.{ }
poolPooling can greatly enhance both the keyed and non-keyed recycle strategy.false
hydrateProgressively enables hydration of already existing DOM structures when mounted. Make sure the existing DOM structure is based on the same template. When something differs from the given template schema, the hydration will stop and silently falls back into the default build strategy.false

Getting Started (Basic Example)

The Mikado Compiler requires Node.js to be installed. This is probably the simplest step in this guide.

Install Mikado from NPM (this will also install the compiler):

npm install mikado

Assume there is an array of data items to render (or just one item as an object):

const data = [{
    username: "User A",
    tweets: ["foo", "bar", "foobar"]
},{
    username: "User B",
    tweets: ["foo", "bar", "foobar"]
},{
    username: "User C",
    tweets: ["foo", "bar", "foobar"]
}];

Accordingly, a template tpl/partial/user.html might look like:

<table>
  <tr>
    <td>User:</td>
    <td>{{ data.username }}</td>
  </tr>
  <tr>
    <td>Tweets:</td>
    <td>{{ data.tweets.length }}</td>
  </tr>
</table>

Compile the template:

In your console type this command line:

npx mikado-compile ./tpl/

Load library and initialize template as ES6 modules:

Load library and initialize template as legacy ES5:




The name of a template inherits from its corresponding filename starting by the folder you've passed through the --src flag when calling the compiler.

After creation, you need mount the Mikado view instance to an HTML element as a destination for your render tasks:

view.mount(HTMLelement);
view.render(data);

You can also chain methods:

Mikado(template).mount(HTMLelement).render(data);

Rules and Conventions

There is just a single convention you always need to keep in mind:

Every template has to provide one single root element as the outer boundary.

Instead of doing this in a template:


  <nav></nav>

<section>
  <p></p>
</section>
<footer>
  <nav></nav>
</footer>

Wrapping everything into a single outer root element by doing this:

<main>
  
    <nav></nav>
  
  <section>
    <p></p>
  </section>
  <footer>
    <nav></nav>
  </footer>
</main>

You can also use a <div> or any other element as a template root (also custom elements). The root element can also hold two special attributes key and cache. We will come later to it.

Advanced Example

A bit more complex template:

<section id="{{ data.id }}" class="{{ this.state.theme }}" data-index="{{ index }}">
  {{@ var is_today = data.date === state.today }}
  <div class="{{ data.class }} {{ is_today ? 'on' : 'off' }}">
    <div class="title" style="font-size: 2em">{{ data.title.toUpperCase() }}</div>
    <div class="content {{ index % 2 ? 'odd' : 'even' }}">{{# data.content }}</div>
    <div class="footer">{{ state.parseFooter(data) }}</div>
  </div>
</section>

You can use any Javascript within the {{ ... }} curly bracket notation. The scope is limited by the template, so variables from one template can't be accessed within another template (use state for this purpose).

To pass HTML markup as a string, the curly brackets needs to be followed by # e.g. {{# ... }}. For better performance, relevant tasks avoid passing HTML contents as a string.

To use Javascript outside an element's context you need to prevent concatenation of the returned value. For this purpose, the curly brackets need to be followed by @ e.g. {{@ ... }}.

Within a template there are several reserved keywords you can use as an identifier:

IdentifierDescription
dataA full reference to the passed data item. Within loops the keyword data points to each of the looped data items.
stateAn optional payload used to manually pass in custom specific values or helper functions. The state will be delegated through all nested templates.
indexRepresents the index of the currently rendered data item (starting by 0 for the first item).
thisProvides you access to the Mikado view instance (e.g. this.state).
windowGives access to the global namespace.
_p
_v
_x
_o
_f
_inc
private identifiers, used by internal processing

You cannot change the names of those preserved keywords, also make sure you didn't override them.

It is recommended to pass custom functions via the state object (see example above state.parseFooter = function(str){ return str; }). Alternatively you can also nest more complex computations inline as an IIFE and return the result.

<div class="date">{{ 
    (function(){ 
        var date = new Date();
        // perform some code ...
        return date.toLocaleString();
    }())
}}</div>

To finish the example from above you need one single data object or an array of data items:

var data = [{
    "id": "230BA161-675A-2288-3B15-C343DB3A1DFC",
    "date": "2019-01-11",
    "class": "yellow, green",
    "title": "Sed congue, egestas lacinia.",
    "content": "<p>Vivamus non lorem <b>vitae</b> odio sagittis amet ante.</p>",
    "footer": "Pellentesque tincidunt tempus vehicula."
}];

Provide the optional state payload which includes specific values and helper methods used within template expressions:

const state = {
  today: "2019-01-11",
  theme: "custom",
  parseFooter: function(data) {
    return data.footer;
  }
};

Mount the view to a target element as a destination for all the render tasks:

view.mount(HTMLelement);

Render a mounted template:

view.render(data, state);

Render asynchronously automatically by just providing a callback function:

view.render(data, state, function() {
  console.log("finished.");
});

To render asynchronously by using promises you need to set the callback value to true:

// callback "true" will use Promises
view.render(data, state, true).then(function() {
    console.log("finished.");
});

// same, but uses async/await:
await view.render(data, state, true);
console.log("finished.");

When async should be the default strategy for all render tasks then you can also set the async option flag:

const view = new Mikado(template, { async: true });
await view.render(data, state);
console.log("finished.");

Compile Templates

Define an HTML-like template and use double curly brackets to markup dynamic expressions which should be calculated and replaced during runtime:

<table>
  <tr>
    <td>User:</td>
    <td>{{ data.username }}</td>
  </tr>
  <tr>
    <td>Tweets:</td>
    <td>{{ data.tweets.length }}</td>
  </tr>
</table>

Save this template e.g. to tpl/partial/user.html

The preserved keyword data is a reference to the passed data item. You can access the whole nested object.

Mikado comes with a builtin template compiler you can simply access by typing npx mikado-compile into your console. The compiler uses a very simple command-line interface (CLI) running on Node.js to perform compilation tasks. The template compiles into a native javascript file which needs to be passed during creation of a Mikado instance. The same markup is also used for the server-side rendering part, so you can share the same template sources for client and server rendering.

Show help to list all available commands:

npx mikado-compile --help

Compile the template through the command line by:

npx mikado-compile tpl/partial/user.html

Basic Notation:

npx mikado-compile source <destination>

When no destination folder was set, the compiled files will be saved to the source folder. After compilation, you will have 3 different files:

  1. list.js the template compiled as a ES6 module (which needs to be imported)
  2. list.es5.js the template compiled as ES5 compatible Javascript (which automatically register when loaded by script tag)
  3. list.html the source template you have implemented (do not delete it)

Extended Notation:

npx mikado-compile --src { source } --dest { destination } --extension html --type module --compact

Compiler Flags:

  • --type module, -t module export as javascript modules (recommended)
  • --type es5, -t es5 export as ES5-compatible package
  • --extension html, --ext html, -e html the file extension which should be compiled
  • --inline, -i or --compact, -c switch the build strategy to optimize either the performance (inline) or size (compact)
  • --force, -f force overwriting existing files
  • --pretty, -p do not minify the compiled result
  • --watch, -w start the watcher for automatically compile when files has changed (just for development purposes)

Supported flags as attributes on the template root:

<!-- switch the build strategy to prebuilt enabled cache -->
<table cache="true"></table>
<!-- switch the build strategy to prebuilt disabled cache -->
<table cache="false"></table>

Using the flag attributes are the most performant variants but also cost you some flexibility, because the cache strategy couldn't be changed in runtime, it needs to change in markup before compilation.

Auto Naming

There is a new naming system which will apply by default. The name of your html files will be used as unique identifiers of your templates. Because several folders can include same filenames, the template name inherits from the full path you pass in as --src.

Assuming the following file structure:

tpl/view/start.html
tpl/view/user.html
tpl/view/cart.html
tpl/partial/start.html
tpl/partial/user.html
tpl/partial/cart.html

The command should define the path /tpl/ as the source root because it is the most inner folder which covers all files:

npx mikado-compile ./tpl/

The template names then becomes view/start, view/user, view/cart and partial/start, partial/user, partial/cart for the partials. So when including just use this name in your expression <table include="partial/user">

The wrong way is to compile the folder /view/ and /partial/ separately, because their template names will be same.

npx mikado-compile ./tpl/view/
npx mikado-compile ./tpl/partial/

This might also work, but it is better not to do.

Prebuilt Cache Strategy

The option { cache: true/false } when creating a Mikado instance could be better declared withing templates on their root element, let the compiler produce more optimized code for this strategy.

<table cache="true">
    <!-- ... -->
</table>

Also use this approach when set cache="false":

<table cache="false">
    <!-- ... -->
</table>

Watcher (Auto-Compile)

A perfect fit for your local development environment is spawning a watcher to automatically compile files when they get changed. Just use the same command line you would also use for a full compilation and append the flag --watch or -w to it:

npx mikado-compile ./tpl/ --watch

Don't close the console, otherwise the watcher will stop. You can stop the watcher explicitly by pressing CTRL + C.

Template Expressions

The template notation expects double curly brackets {{ ... }} for any kind of dynamic expressions.

Except when using {{@ ... }} for inline code notation, the returned value of every dynamic expression will be replaced to its position.

Value Insertion {{ ... }}

<div>{{ data.value }}</div>
view.render({ value: "test" });

You can also combine multiple expressions with non-expression contents:

<div>The title "{{ data.title }}" has the value: {{ data.value }}</div>
view.render({ title: "title", value: "test" });

You can also mix text nodes with elements on the same root element:

<div>Title: <b>{{ data.title }}</b><br>Value: {{ data.value }}</div>
view.render({ title: "title", value: "test" });

Also, you can use expressions within every attribute:

<div data-id="{{ data.title }}" class="{{ data.class }}">{{ data.value }}</div>
view.render({ id: 1, value: "test", class: "test" });

Every Javascript syntax is allowed withing expression:

<div style="color: {{ data.active ? 'green' : 'black' }}; {{ data.value ? '' : 'display: none;' }}"></div>
view.render({ active: true, value: "not empty" });

Since expressions just need to return a value you can also use IIFE:

<div>{{ 
    (function(){ 
        var date = new Date();
        // perform some code ...
        return date.toLocaleString();
    }())
}}</div>
view.render();

JS Inline Code {{@ ... }}

The inline code expression is the only one which doesn't return a value to be rendered in place, it just executes.

<div>
    {{@ const value = data.title.toUpperCase(); }}
    <h1>{{ value }}</h1>
</div>
view.render({ title: "title" });

The scope is limited to the template scope, but you can assign to state alternatively to share values across nested instances:

<div>
    {{@ state.value = data.title.toUpperCase(); }}
    <div include="header">
        <!-- contents of header.html:
        <h1>{{ state.value }}</h1>
        -->
    </div>
</div>
view.render({ title: "title" });

Truthy Values {{? ... }}

This will just output the result when it is not null, undefined, NaN or false.

<div>{{? data.value }}</div>
view.render([{
    value: null
},{
    value: NaN
},{
    value: undefined
},{
    value: false
}]);

Escape Values {{! ... }} (SSR only)

This will escape the value before return. This is just important for the server-side-rendering part, the client automatically escape contents by default (except when using the HTML-expression).

<div>{{! data.value }}</div>
view.render({ value: "<b>html is not allowed</b>" });

HTML Contents {{# ... }}

This will allow for inserting HTML returned string.

Be aware of this can potentially lead into security issues like XSS. Use carefully!

<div>{{# data.value }}</div>
view.render({ value: "<b>html is allowed</b>" });

Sanitizer

Mikado provides you high performant helper function you can use in this context to escape contents or to sanitize.

view.render({ 
    value: "<b>html allowed</b><br>" + Mikado.escape("<b>not allowed</b>")
});
view.render({ 
    value: "<b>html allowed</b><br>" + Mikado.sanitize("<b>not allowed</b>")
});

Using the sanitizer will remove the tags completely, whereas when escaping the content aren't removed but just escaped.

Reactive Bindings {{= ... }}

Define properties by using pure data object notation without any javascript inside:

<div class="{{= data.class }}">{{= data.value }}</div>
// store must be an array of elements:
const store = [{ class: "active", value: "foo" }];
// it needs a initial render if store isn't empty:
view.render(store);
// the store array now was proxified!

Now you can change the properties of store and the corresponding DOM elements will change automatically:

store[0].class = "inactive";
store[0].value = "bar";

Runtime Compiler

Alternatively of using the npx mikado-compile you can also compile templates during runtime.

If a page has set a Content-Security-Policy (CSP) header field, using the runtime compiler has disadvantage when not configure script-src 'unsafe-eval'. It is recommended to use the Mikado native compiler, which is CSP-friendly and also can optimize your templates more powerful.

The runtime compiler uses the performance optimized inline strategy for every task, you can't switch it. The compiler property flag cache="true" or cache="false" on a template root is not supported, therefore you can't use 2 of the most performant strategies. But they are just slightly faster, so this shouldn't be an issue.

Those features aren't supported by the runtime compiler:

  • cache="true" or cache="false" on a template root
  • using any other compiler strategy than inline
  • detect and replace repeating inline includes
  • detect and solve/unroll non-dynamic expressions, e.g. <h1>{{ "foor" + "bar " }}</h1> will transform to a static content <h1>foobar</h1> and removes the expression completely
  • runtime-ready templates aren't available on page load (they need to compile)
  • the runtime compiler does not pass the "crazy template" test

Examples

Define some HTML template structure:

<template id="user-list">
  <!-- just a single outer root element allowed: --> 
  <table>
    <tr>
      <td>User:</td>
      <td>{{ data.user }}</td>
    </tr>
    <tr>
      <td>Tweets:</td>
      <td>{{ data.tweets.length }}</td>
    </tr>
  </table>
</template>

Template definitions used by the runtime compiler needs manual naming when used as named includes.

The template name will derive from <template id="user-list"> or <template name="user-list"> and becomes user-list. When using named includes you will need to use this name for referencing, e.g. <div include="user-list">".

Compile the template and use it for creating a Mikado view instance:

const template = document.getElementById("user-list");
const tpl = Mikado.compile(template);
const view = new Mikado(tpl, { /* options */ });

view.render(data);

When the template was get through element ID you can use a shortcut:

const tpl = Mikado.compile("user-list");

Also, you can compile the template and use it for registration as a named include referenced by another template e.g. <div include="user-list">":

Mikado.register(Mikado.compile("user-list"));

You can use non-template elements for defining templates also:

#user-list{ display: none }
<!-- just a single outer root element allowed: --> 
<table id="user-list">
  <tr>
    <td>User:</td>
    <td>{{ data.user }}</td>
  </tr>
  <tr>
    <td>Tweets:</td>
    <td>{{ data.tweets.length }}</td>
  </tr>
</table>

Last but not least you can pass the template markup as a string:

const tpl_str = `
<table name="user-list">
  <tr>
    <td>User:</td>
    <td>{{ data.user }}</td>
  </tr>
  <tr>
    <td>Tweets:</td>
    <td>{{ data.tweets.length }}</td>
  </tr>
</table>`;

const tpl = Mikado.compile(tpl_str);
const view = new Mikado(tpl, { /* options */ });

view.render(data);

Using Inline Code

The runtime compiler does not support all places of inserting inline code expressions. In some situations it might produce issues like here:

<table id="user-list">
  <tbody foreach="data.entries">
  {{@
    /* the browser will move this before <table>! */ 
    const value = "test";
  }}
  <tr>
    <td>Value: {{ value }}</td>
  </tr>
  </tbody>
</table>

The runtime compiler didn't parse the template by string, instead the compiler creates a dom structure when passing a template as string. On the example above the {{@ ... }} expression is treated as a text node by the browser. Since the position isn't allowed to place text nodes (after <table>, <tbody>, <tr>) the browser moves this text node up to the outer scope of the table. But the inline code is now executed within the first outer template function, instead the inline loop template function needs the value and is running in its own scope.

In this situation you can store values on state to pass through inline looped partials. Or you can use the ` Value: {{ value }}

```

Don't forget to use the expression notation, otherwise it will be inserted as a normal code element.

When the `

```

You can't use any template expressions outside <template/>.

You can also render any normal template (non-components) to a plain dedicated shadow root by using the shadow: true option (also supported by the light bundle):

const view = new Mikado(tpl, { shadow: true });

Theoretically you can put the ``, <style/> and ` {{ index + 1 }} {{= data.title }} {{# data.media }} {{? data.category }} {{! data.comment }} {{ datestr }} No entries found.

```

A proper definition and call for this template could look like this:

// the named include "pager" needs to be registered before use
Mikado.register(tpl_pager);

// define route "select-active"
view.route("select-active", function(target, event){
    const id = Number(target.dataset.id);
    view.state.selected = id;
});

view.render({
  view: "video",
  entries: [{
    id: 1,
    date: "2023-12-01T14:00:00",
    title: "A simple title 1",
    media: "<img src='img1.jpg'>",
    category: null,
    comment: "Some  content",
    mode: "off"
  },{
    id: 2,
    date: "2023-12-02T15:00:00",
    title: "A simple title 2",
    media: "<video src='mov2.mp4'>",
    category: null,
    comment: "Some  content",
    mode: "on"
  },{
    id: 3,
    date: "2023-12-03T16:00:00",
    title: "A simple title 3",
    media: "<img src='img3.jpg'>",
    category: null,
    comment: "Some  content",
    mode: "off"
  }]
});

Each template part explained:

  • cache="true" let the compiler prebuilt the cache strategy, you can't switch it to off when creating an instance
  • id="{{ data.view }}" simple expression for inserting dynamic content
  • if="!data.entries.length" the if-directive checks the condition and will render everything nested as a new template (inline definition or extern by using "include"), the nested template needs to have one outer element as the root
  • foreach="data.entries" the foreach-directive loops the rendering of array items by everything nested as a new template (inline definition or extern by using "include"), the nested template needs to have one outer element as the root
  • {{@ ... }} an expression to include pure javascript syntax (access limited by the scope of the template), wrapped into a <script/> tag just for runtime compiler support.
  • key="data.id" extract the key value from the data, a given key is limiting the recycling of already rendered components by a keyed strategy
  • data-id="{{ data.id }}" root exports "data.id" as an attribute, also define "root" as the event target for the listener "select-active", pretty useful when multiple routes on different elements needs the same data attributes
  • {{ index + 1 }} uses the builtin keyword "index" which refers to the current index of looped data
  • {{= data.title }} uses reactive approach by binding the html node to the data field, so when changing the data data.title ="another title" the node contents will also change accordingly
  • {{# data.media }} allows to include html syntax (this is unsafe, don't pass user inputs, you will need to prevent XSS by yourself)
  • {{? data.category }} only prints a "truthy" value including 0 (skips undefined, null, NaN, false)
  • {{! data.comment }} escape the value before print out (SSR only)
  • {{ datestr }} access the variable which was created by inline syntax before
  • style="opacity: {{ state.selected === data.id '1' ? '0.5' }}" example of dynamic attribute value
  • change="select-active:root" assign the route named "select-active" and forward the event to the element which has the given attribute name assigned to it or in this case "root" points to the components root (so the target inside the root function becomes the forwarded element)
  • selected="data.active === 'yes'" when dynamic attribute values results to boolean "false" (not string) it will be removed from the element, because some attributes enables just by their existence (consider an option element having selected="false" will end up also as a truthy selection state)

Concept of Shared Components

Mikado heavily makes use of runtime optimization. Since it is not possible to predict the recycle state of the next render task, Mikado uses a technique called progressive enhancement on which optimizations will apply iteratively. Recycle enhancements growth as needed.

The most benchmarks you will find ends at the point where Mikado starts to shine. Rendering a simple table isn't really a complex task. Real applications have bigger structures including partials, includes, conditionals, etc. The concept of shared components was the basic idea of this library. It is the "ultimate" upgrade of the recycle paradigm and when properly used, it is one of the biggest optimization improvement you can unlock.


Mikado Shared Components (Concept)

Mikado will take away every complexity you might expect of such a system. You just need to structure your HTML templates and use .render(data), that's it!

Custom Builds

The src folder of this repository requires some compilation to resolve the build flags. Those are your options:

  • Closure Compiler (Simple or Advanced, used by this library, example)
  • Babel + Plugin babel-plugin-conditional-compile (used by this library here)

As far as I know you can't resolve build flags with:

  • Webpack
  • esbuild
  • rollup
  • Terser

Please let me know when you have some additions. As long as you will see flags like if(DEBUG) (could be minified) in your build you shouldn't use that.

These are some of the basic builds located in the dist folder:

npm run build:bundle
npm run build:light
npm run build:module
npm run build:es5

Perform a custom build (UMD bundle) by passing build flags:

npm run build:custom SUPPORT_CACHE=true SUPPORT_POOLS=true LANGUAGE_OUT=ECMASCRIPT5 POLYFILL=true

Perform a custom build in ESM module format:

npm run build:custom RELEASE=custom.module SUPPORT_CACHE=true SUPPORT_POOLS=true 

Perform a debug build:

npm run build:custom DEBUG=true SUPPORT_CACHE=true SUPPORT_POOLS=true 

On custom builds each build flag will be set to false by default when not passed.

The custom build will be saved to dist/mikado.custom.xxxx.min.js or when format is module to dist/mikado.custom.module.xxxx.min.js (the "xxxx" is a hash based on the used build flags).

Supported Build Flags
FlagValuesInfo
DEBUGtrue, falseOutput debug information to the console (default: false)
SUPPORT_CACHEtrue, falseDOM State Cache
SUPPORT_EVENTStrue, falseRouting & Event Delegation (template event bindings)
SUPPORT_KEYEDtrue, falseSupport for keyed recycling (reconciliation)
SUPPORT_WEB_COMPONENTStrue, falseSupport for web components (Shadow DOM)
SUPPORT_DOM_HELPERStrue, falseDOM Manipulation Helpers
SUPPORT_CACHE_HELPERStrue, falseDOM Cache Helpers
SUPPORT_ASYNCtrue, falseAsynchronous Rendering (support Promises)
SUPPORT_POOLStrue, falseSupport component pools for keyed and non-keyed recycle strategies
SUPPORT_REACTIVEtrue, falseUse reactive data binding
REACTIVE_ONLYtrue, falseUse a full reactive approach for all views, exclude .render() and dependencies from build (default: false)
SUPPORT_CALLBACKStrue, falseUse callbacks for specific render tasks
SUPPORT_COMPACT_TEMPLATEtrue, falseTurn on when templates are compiled with the compact or default strategy
SUPPORT_COMPILEtrue, falseUse the runtime compiler

Compiler Flags
RELEASE




custom
custom.module
bundle
bundle.module
es5
light
Output debug information to the console (default: false)
POLYFILLtrue, falseInclude Polyfills (based on LANGUAGE_OUT)
PROFILERtrue, falseJust used for automatic performance tests
LANGUAGE_OUT










ECMASCRIPT3
ECMASCRIPT5
ECMASCRIPT_2015
ECMASCRIPT_2016
ECMASCRIPT_2017
ECMASCRIPT_2018
ECMASCRIPT_2019
ECMASCRIPT_2020
ECMASCRIPT_2021
ECMASCRIPT_2022
ECMASCRIPT_NEXT
STABLE
Target language

Copyright 2019-2024 Nextapps GmbH
Released under the Apache 2.0 License

Dự án tương tự

Khám phá các dự án và mô hình AI khác có sự tương đồng.

RepositoryJavaScript
handlebars-lang/handlebars.js

Minimal templating on steroids.

18.7k
Oct 6, 2026
RepositoryJavaScript
handlebars-lang/handlebars.js

Minimal templating on steroids.

18.7k
Oct 6, 2026
RepositoryC#
scriban/scriban

A fast, powerful, safe and lightweight scripting language and engine for .NET

4.0k
Nov 22, 2026
RepositoryC#
Handlebars-Net/Handlebars.Net

A real .NET Handlebars engine

1.5k
Nov 26, 2026
RepositoryC#
Handlebars-Net/Handlebars.Net

A real .NET Handlebars engine

1.5k
Nov 26, 2026
RepositoryJavaScript
markmead/alpinejs-tash

Use a more familiar syntax when rendering Alpine JS {variables} 🚀

120
Dec 1, 2026
RepositoryPython
pallets/jinja

A very fast and expressive template engine.

11.8k
Jun 14, 2025
RepositoryPHP
twigphp/Twig

Twig, the flexible, fast, and secure template language for PHP

8.4k
Nov 24, 2026
RepositoryGo
Masterminds/sprig

Useful template functions for Go templates.

4.8k
Jul 18, 2025