Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

In programming web applications is often useful to be able to have a templating function.

This is a templating function (rather a library) that aligns with goals of doing things simply from first principles avoiding complexity, safety by design and separation of concerns.

This is how one would use such a template:

Code Block
languagejs
var MAINtemplate=
`<p>$Name$ has $$$Amount$ in their bank account.</p>$
 <p>----</p>$`p>
`;

function MAINrun(){
   var Body = document.querySelector('body');
   var Data = [{Amount : 55, Name : " Fred " }, {Amount : 45 , Name : "Mary"}];
   Body.innerHTML = TEMexpand(Data, MAINtemplate);
}

READYevent(MAINrun);

This code would produce

What are the advantages compared to using a more fully featured templating system like Mustache?

  • All data is automatically escaped for special HTML characters. This eliminates cognitive load of having to pick whether or not to escape data and eliminates a lot of bugs.

  • The library is small - you can see exactly what it does in one screenful of code. No big mysteries as to what it does

  • Zero fancy features - nothing whatsoever resembling a language with if conditionals and so on. Therefore zero danger of the templating library becoming a crappy language.

    • There are no fancy callback features to tempt developers to write complicated code. It’s only going to work with an array of data.

    • No caching or other unnecessary pre-mature optimizations - simple code will be faster anyway.

  • Putting the responsibility elsewhere for handling logic in absence of data etc. Encouraging separation of concerns.

The code does use some techniques which are worth understanding:

...

We use an array of string and concatenate them at the end for performance.

...

We escape characters like & < and > to translate into HTML entities so that data can be not mis-interpreted and HTML markup.

...

:

Code Block
Fred has $55 in their bank account.
----
Mary has $45 in their bank account.
----

TEMexpand is implemented couple of dozen lines of code. You can get the source here.

So why use this instead of a fully featured templating system like Mustache?