gmosx

Normal Template

by gmosx, at 25 Jan 2010
For some time now I was using a custom version of JSON-Template. I really like the simplicity of JSON-Template and the clean separation of data, logic and design. On the other hand I hate the syntax (repeated section, argh) and the 'cursor' paradigm employed has problems in practice.

In this vein, I designed a new template engine, called Normal Template. I consider this an evolution of JSON-Template concepts that works better in practice. Here are some benefits:

  • Separate 'if' command (required in practice)
  • Replaced {} interpolation with {=..}, safer in practice, more readable
  • A subset of XPath is used to navigate the data dictionary along with a cursor model (select)
  • Abbreviations for tags (s for select, r for reduce, etc)
  • Meta templates and static includes
  • Compiles to a javascript function for extra performance
  • Improved syntax error checks and reporting

For more information, please consult the detailed docs. To wet your appetite, here is an example:

template.html:

<html>
<h1>Hello {=name}</h1>
 
{:select profile}
<p>
    {=age}<br/>
    {=gender}<br/>
</p>
{/:select}
 
<p>Your age is {=profile/age}</p>
 
<ul>
{:reduce articles}
    <li>{=title} - {=count}</li>
{:else}
    <li>No articles found</li>    
{/:reduce}
</ul>
 
{:if admin}
    You have admin rights
{:else}
    You don't have admin rights
{/:if}
</html>

template.js:

var data = { // the data dictionary in JSON format
    name: "George",
    profile: {
        age: 34,
        gender: "M"
    },
    articles: [
        { title: "Hello world", count: 34 },
        { title: "Another article", count: 23 },
        { title: "The final", count: 7 }
    ],
    admin: true
}

4 Comments

by tkouts, at 25 Jan 2010
I really like this template engine.
It seems as simple enough as it should be, robust and readable.
I'll make a python port and include it in porcupine since it still lacks a template engine.
by George Moschovitis, at 25 Jan 2010
A port to python would be great! You can contact me for help...

Anyone would like to try a Ruby/Java port?
by George Moschovitis, at 25 Jan 2010
I hope to clean up the code a little bit, and add support for custom tags/commands (for example a localization tag), stay tunned...