Sunday, September 2, 2012

Handlebars and Ember templating in Window 8 Metro

Handlebars uses script blocks for template markup. E.g.

<script type="text/x-handlebars" data-template-name="say-hello">
      Hello, <b>{{MyApp.name}}</b>
</script>

Unfortunately the Metro JavaScript engine removes the data-template-name attribute from the script tag, so this method can’t be used for templating.

As JS files are available locally for execution, the template files can be stored in separate HTML files and can be parsed from code. The implementation is simple:

        

Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync(path).done(function(folder) {
    var search = folder.createFileQuery(Windows.Storage.Search.CommonFileQuery.orderByName);
                search.getFilesAsync().done(function (res) {
                        res.forEach(function (file) {
                                var template;
                                Windows.Storage.FileIO.readTextAsync(file).then(function(fileContent) {
                                       var template = Ember.Handlebars.compile(fileContent);
                                       Ember.TEMPLATES[file.displayName] = template;
[…]

I omitted the async promises from the code for readability, but the code won’t work without them.

The code above

  1. reads all the files from a folder
  2. compiles the template
  3. stores the compiled template as an Ember template

Now Ember.js and Handlebars.js are fully functional, even Ember.View can be used with view.append().