Search This Blog

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.

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.

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.

Popular posts from this blog

Now, this has to have a built-in somewhere in Scala , because it just seems too common. So, how to convert an Array to a List in Scala? Why do I need this? I needed to drop to Java for some functionality, which in this case returns an Array. I wanted to get that Array into a List to practice my functional programming skillz. **Update**: I figured out how to convert Arrays to Lists the Scala way. Turns out it's a piece of cake. val myList = List.fromArray(Array("one", "two", "three")) or val myList = Array("one","two","three").elements.toList The call to elements returns an Iterator , and from there you can convert to a List via toList . Nice. Because my first version wasn't actually tail recursive, what follows is a true tail recursive solution, if I were to implement this by hand. The above, built in mechanism is much better, though. object ArrayUtil { def toList[a](array: Array[a]): List[a] = { d

In which I port a snazzy little JavaScript audio web app to Dart , discover a bug, and high-five type annotations. Here's what I learned. [As it says in the header of this blog, I'm a seasoned Dart developer. However, I certainly don't write Dart every day (I wish!). Don't interpret this post as "Hi, I'm new to Dart". Instead, interpret this post as "I'm applying what I've been documenting."] This post analyzes two versions of the same app, both the original (JavaScript) version and the Dart version. The original version is a proxy for any small JavaScript app, there's nothing particularly special about the original version, which is why it made for a good example. This post discusses the differences between the two implementations: file organization, dependencies and modules, shims, classes, type annotations, event handling, calling multiple methods, asynchronous programming, animation, and interop with JavaScript libraries. F

In which the virtues of automated mechanical arboreal pruning are extolled over quaint manual labor, as applied to web development build processes. The setup Ever notice how the primary bit of marketing for many traditional web programming libraries is their download size? Why is that? Check this out: Why does size matter so much for these libraries? Your first instinct is probably, "because the more bytes you shuttle across the wire, the slower the app starts up." Yes, this is true. I'd also say you're wrong. The primary reason that size matters for these libraries is because traditional web development has no intelligent or automated way to prune unused code so you can ship only the code that is used over the wire. The web is full of links, yet web dev has no linker The web development workflow is missing a linking step. A linker's job is to combine distinct project files into a single executable. A smart linker will only incl