First look at Dart's HTML template library

UPDATE: Work on this library has stopped. You probably want to see Polymer or Angular.

Note: this is very very early access stuff. Feedback most welcome!

Dart is built to help developers build modern web apps. With today's commit of an HTML template library, that job just got a little bit easier. I take a first look at this new (and still evolving) template library to see what it does and how it works.

This week has been full of great stuff in the Dart community. Just a sample: Lars Bak and Kasper Lund join the JavaScript Jabber podcast, support for adjacent string literals lands in the Dart Editor, and the article I co-authored titled What is Dart? was published by O'Reilly. With this new template library, it looks like there is no slowing down.

Intro

Modern web apps process data and generate display content on the client. The days of full page refreshes and expensive server round trips are gone. Modern web app frameworks usually ship with some sort of template option, to ease the burden of constructing lengthy DOM. Whether you use a template system or construct the DOM programmatically with Views, it's much better to not have to ask the server for HTML.

The Dart engineers have just checked in a preview of their template system, specifically targeting HTML applications. It converts blocks of HTML text, sprinkled with interpreted directives, into Dart classes ready to generate DOM nodes for insertion into your app.

Getting started

This project is not yet part of the SDK, so you'll need to sync to the bleeding_edge branch from the Dart source repository, as of 2012-03-15. Look inside util/tests/template and util/template for the examples, tests, libraries and binaries.

Hello, templates

Here's what a simple template file looks like:

template Hello(String to) {
  <div>${to}</div>
}

Note this is not "Dart code" and does not live in a .dart file. Instead this is a Dart template, and lives in a .tmpl file.

The template is compiled into a Dart class, to be used by your program. The name of the template, in this case Hello, becomes the name of the class. The arguments to the template, in this case String to, become the constructor arguments.

Compile the template into a Dart class with the following command. It assumes you have the Dart VM on your PATH.

$DART_REPO/dart/util/template hello.tmpl

This will generate a hello.dart file containing a Hello class. We'll look inside the hello.dart file in a moment, for now let's keep going.

Next, you'll build your sample Dart script. We'll keep this very simple:

#import('dart:html');
#source('hello.dart'); // generated by the template engine

main() {
  Hello hello = new Hello("Bob"); // created from the template
  document.body.elements.add(hello.root);
}

Our sample script sources the hello.dart file, making it available to this script. We then construct a new instance of Hello and attach its root element to the document's body.

Next, compile your simple Dart script (assuming frogc, the Dart to JavaScript compiler, is on your PATH);

frogc test-hello.dart

Next, create a simple HTML file to host the script:

<!DOCTYPE html>
<html>
<head>
  <title>Template Test</title>
</head>
<body>
<script type="text/javascript" src="test-hello.dart.js"></script>
</body>
</html>

Loading the page and executing the script will use the template to populate the document's body:

<!DOCTYPE html>
<html>
<head>
  <title>Template Test</title>
<style></style></head>
<body>
<script type="text/javascript" src="test-hello.dart.js"></script>
<div id="hello">Bob</div>
</body>
</html>

Notice the new <div> in the page!  Cool!

The Hello class walkthrough

The template itself is compiled into a class. Let's look at that class by breaking it down.

First we see a handy utility method to strip strings of XSS vulnerabilities. Or, at least we find the placeholder to do that. :) Glad to see the templates taking XSS seriously. I also like to see Dart code that uses top level functions,  for not everything in Dart needs to be a class.

String safeHTML(String html) {
  // TODO(terry): Escaping for XSS vulnerabilities TBD.
  return html;
}

Next up is the actual Hello class. Instead of breaking up the class, I added comments for inline commentary.

class Hello {
  // SETH: this is what your template hangs off of.
  // SETH: This never touches the DOM.
  Element _fragment;

  String to;

  // SETH: this name comes from the template
  Hello(this.to) {
    // SETH: templates can inject stylesheets. Example to follow.
    // Insure stylesheet for template exist in the document.
    add_hello_templatesStyles();

    _fragment = new Element.tag('div');

    // SETH: here's the template! Notice the string interpolation
    var e0 = new Element.html('<div>${inject_0()}</div>');
    _fragment.elements.add(e0);
  }

  // SETH: how to access the nodes from the template.
  // SETH: Still not attached to DOM.
  Element get root() => _fragment.nodes.first;

  // Injection functions:
  String inject_0() {
    return safeHTML('${to}');
  }

  // Each functions:

  // With functions:

  // SETH: our template didn't define any CSS, so this is empty
  // CSS for this template.
  static final String stylesheet = "";
}

Accessing specific HTML elements

The template system is more expressive than our simple example shows.

You can bind individual elements to variables for easy access by your Dart code. Any HTML tag with a var attribute will be directly accessible by a variable on the template class.

For example:

template Hello(String to) {
  <div var=hello>
    <p var=p>${to}</p>
  </div>
}

Compiling the above template will generate the following output:

class Hello {
  Element _fragment;

  String to;

  // Elements bound to a variable:
  var hello;
  var p;

  Hello(this.to) {
    // Insure stylesheet for template exist in the document.
    add_hello_templatesStyles();

    _fragment = new Element.tag('div');
    hello = new Element.html('<div></div>');
    _fragment.elements.add(hello);
    p = new Element.html('<p>${inject_0()}</p>');
    hello.elements.add(p);
  }

Which means you can now access these elements directly in your script:

main() {
  Hello hello = new Hello("Bob");
  hello.p.on.click.add((e) => print('clicked on paragraph!'));
  document.body.elements.add(hello.root);
}

Loops

You can loop over a collection, but there doesn't seem to be a way to print the value from a simple list of Strings or numbers (this is a known bug, it's on the short short list). For now, you can loop over objects with fields and print the fields, though:

template Applications(var products) {
  <div>
    ${#each products}
      <div>
        <span>${name}</span> <!-- similar to product.name -->
        <span>-</span>
        <span>${users}</span>
      </div>
    ${/each}
  </div>
}

Summary

The Dart templates library is brand new, and should be considered technology preview just like anything else in the Dart project.

The template library is specialized for constructing HTML sub trees for inclusion in your client side web app. Your template files, which include HTML tags and text, are compiled into Dart classes which construct DOM elements.

Please give it a shot and let us know what you think by joining the mailing list or file a bug or feature request.

Popular posts from this blog

Lists and arrays in Dart

The 29 Healthiest Foods on the Planet

Converting Array to List in Scala