Mooml: Mootools markup language (intro)

Jan 17 2010

It was a month ago when I found about Jaml, an excellent small Javascript library created by Ed Spencer which allows generating HTML code using very nice and clean templates. At work we use Mootools in most of our projects, so I thought it would be nice to improve Jaml by taking advantage of the power of Mootools. And this is the result.

Mooml: Mootools markup language

What is Mooml? Mooml is a templating system that allows generating HTML snippets very easily, without all the ugly nested “new Element” calls or string concatenation. With Mooml you can save templates for later use or evaluate snippets on the fly.

Download: http://mootools.net/forge/p/mooml
Source: http://github.com/eneko/mooml

Let’s see an example

Required HTML:

  1. <div class="node">
  2.   <h2>Node Title</h2>
  3.   <p>Node body here.</p>
  4. </div>

Node title and body are variables, so let’s save them on a Json format for now.

  1. var data = {
  2.   title: 'Node Title',
  3.   body: 'Node body here'
  4. }

Using Mootools “new Element” we would have to code something like this:

  1. var el = new Element('div', {'class': 'node'}).adopt([
  2.   new Element('h2', {text: data.title}),
  3.   new Element('p', {text: data.body})
  4. ]);

That code is much better than plain Javascript, but still messy. We could use the new Elements.from included in Mootools More 1.2.4, but that would require us writing the html as a string, which rapidly gets messy concatenating variables, etc.

  1. var el = Elements.from('<div class="node"><h2>' + data.title + '</h2><p>' + data.body + '</p></div>');

With Mooml…

With Mooml, we can create a template for that piece of code, and reuse it later as many times as we need:

  1. Mooml.register('node', function(data) {
  2.   div({'class': 'node'},
  3.     h2(data.title),
  4.     p(data.body)
  5.   )
  6. });
  7. document.body.grab(Mooml.render('node', data));

We can also execute the template directly as a function:

  1. document.body.grab(Mooml.templates.node(data));

Finally, with Mooml we can evaluate templates on the fly, without having to store them for later:

  1. document.body.grab(Mooml.evaluate(function(data) {
  2.   div({'class': 'node'},
  3.     h2(data.title),
  4.     p(data.body)
  5.   )
  6. }, data));

More examples soon :)

Related Posts:

One response so far

  1. [...] Eneko Alonso ported the project to MooTools, creating mooml [...]

Leave a Reply