Instalation
npm i -D mithril-template
Usage
var mithrilTemplate = console
Template syntax- guide
Interpolation
The most basic form of data binding is text interpolation using the “Mustache” syntax (double curly braces):
Hello {{ name }}!
that will output:
Awesome, right? So let's dive deeper.
Interpolations can't be used within html tag definiition (also in attributes), so this code is invalid:
Hello World!
instead use a binding attribute:
Hello World!
output:
Note that {
and }
characters are reserved in templates for interpolation, so if you have to write them use this workaround:
This is how to use {{ "{" }} and {{ "}"+"}" }} chars.
You can't use {
and }
html entities because mithril will escape them
Eembeding components
To embed component, his name must end on -component
, be kebab-case (a.k.a. snake-case) that will be automatically converted to camelCase and can't be self-closed tag:
output:
Attributes that are not followed by :
(colon) will be ommited.
output:
so if you want to pass data into component use binding syntax instead:
output:
You can nest anything inside the component:
Hello!
output:
Nested data will be available in vnode.children
component view property:
<!--customComponent view-->{{ vnode.children[0] }}
output:
Binding attributes
You probably noticed that html attributes are compiled to hardcoded selectors:
output:
if you want to bind html attribute just put :
(colon) before attribute name:
output:
you can also bind events and lifecycle hooks:
Hello World!
output:
Directives
Directives are putted as html attributes that are previxed by *
(asterisk).
The result hyperscript code will be surrounded by javascript flow statements.
There are four available directives, that can be mixed togheder:
for
if
elseif
else
Let's explain, but note that examples' outputs below are unminified, for better readability.
if:
usage:
odd
output:
varr % 2 == 0 ? : ""
if-elseif && if-else:
odd divisible by 5 other
output:
varr % 2 == 0 ? : varr % 5 == 0 ? :
for:
{{ item.name }}
output:
for with index:
#{{ index }}: {{ item.name }}
output:
for-else
for loop can be used with else (or elseif) statement:
#{{ index }}: {{ item.name }} items not found
output:
so if items array is empty (loop won't execute even once) then else statement will be executed
Traps
To maximally compress output- whitespaces whose belongs to tags are not properly handled, so if you write this code:
foo bar baz qux
the transpiled code will be:
"foo""baz qux"
instead of:
"foo "" baz qux"
that you may expected. So if you need space between text and tag do it by this workaround:
foo{{ " " }}bar{{ " " }}baz qux
Additional advantages
- properly support splats for better minification
- produce maximally minified js code (also minify literal selectors)