Wednesday, March 28, 2012

Dart's new template engine

Dart's new template engine seems promising.
I really like the fact that the new Dart template engine generates a *tree* rather than a string. Or more specifically, an html.Element. Other than XSLT, this is the only templating system i know of that does this.
This comes very close to something i have been wanting for a long time, what i call: "typed templates" or "extensible literal types"
Whether we call them XML literals or DOM (typed) templates, the idea is the same.

Suggestions for Improvement

There are four things i think that would improve Dart's template engine:
1. Eliminate the extra compile step. i.e. with something like #source or #import. Maybe:

#template("myTemplates.tmpl");
2. Leave the door open for other template types. i.e. provide some way to specify the returned type and/or the template engine to use. So, instead of this:
template Hello(String to) {
  <div>${to}</div>
}
we would have this:
html.Element htmlTemplate Hello(String to) {
  <div>${to}</div>
}
where html.Node is the return type and html is the template engine.
Or if the template engine type implies the return type you can skip that part:
htmlTemplate Hello(String to) {
  <div>${to}</div>
}
Other examples:
xmlTemplate Hello(String to) {  }
sqlTemplate oldPeople(int minAge) {  }
jsonTemplate Hello(List<Person> people) {}
stringTemplate emailTemplate(Person p) {}
daveDslTemplate(Person p){}
3. An extension mechanism.
For common DSL's (initially just html) the template engine would be built-in. But one could provide a custom template engine like this:
4. In-line templates. This one is a stretch, but it would be nice if templates could be defined in a .dart file alongside other dart code:
//normal dart function
Person getPerson(){
        //yada yada
}
//dart template function
htmlTemplate Hello(String to) {
  <div>${to}</div>
}
I know the whole language in a language (island grammars) complicates things from the dart parser/vm perspective. So this is a nice-to-have more than a must-have.

No comments: