Dart templates now allow nesting

UPDATE: Work on this library has stopped. You probably want to see Web UI, the fully supported modern client-side library for dynamic, data-driven web apps.

Just a few days after we see the first hints at a Dart template library, new features and fixes have landed to make Dart templates even more useful. This is Part 2 of our exploration of Dart templates, read Part One for an introduction to Dart templates.

Included in this new commit are:
  • fixed bug with whitespace being removed from text nodes
  • added local names for #with and #each
  • added ability to call another template from within a template
Let's take these new features for a spin.

Local names

Using local names, we can loop through a simple List of Strings.  For example, given the following simple script:

#import('dart:html');
#source('hello.dart');

main() {
  List fruits = ['apples', 'oranges', 'bananas'];
  Hello hello = new Hello("Bob", fruits);
  hello.p.on.click.add((e) => print('clicked on paragraph!'));
  document.body.elements.add(hello.root);
}

Here's the template the goes along with the above code:

template Hello(String to, List fruits) {
  <div var=hello>
    <p var=p>${to}</p>
    <p>My favorite fruits are:</p>
    <ul>
      ${#each fruits fruit}
      <li>${fruit}</li>
      ${/each}
    </ul>
  </div>
}

The new syntax for #each is now #each collection [item] where item is an optional name for the current item. This allows, among other things, iteration over simple Dart collections.

Calling other templates

Another new feature allows for calling a template from another template. Here's an example of a single .tmpl file containing two templates, with the first calling the second.

template Hello(String to, List fruits) {
  <div var=hello>
    <p var=p>${to}</p>
    <p>My favorite fruits are:</p>
    ${#Fruit(fruits)}
  </div>
}

template Fruit(List fruits) {
  <ul>
    ${#each fruits fruit}
    <li>I do love eating a fresh, ripe ${fruit}</li>
    ${/each}
  </ul>
}

I think there are still a few kinks to work out here, but nice to see some composability with templates.

Next up

More CSS features to support name mangling is on the TODO list. What else do you want to see from Dart's template library?

Summary

Dart's template library is optimized for rich client web apps. Given a file containing HTML snippets, the Dart template library will generate Dart classes that programmatically generate the HTML elements.
7 comments

Popular posts from this blog