Since we’re using Ember we wanted to tap in to the play asset compilation system to precompile our ember templates on the server before sending them to the client. This has a number of advantages over client-side compilation, allowing us to catch template errors at build time and to eliminate the runtime overhead of template compilation in the client.
The template compiler we created looks at the setting
emberEntryPoint, which should be a sequence of directories containing ember templates (note that this is different from the standard asset compilers which have files as entry points, rather than directories). For each entry point directory, we compile all the
For example, suppose we have the following hierarchy of files:
app/ assets/ templates/ my_view.handlebars widget/ another_view.hanblebars
We set the
app/assets/templates; the compiled template file will be served from
templateName property on your ember views, for example:
Note that the hierarchy of template files is preserved in the compiled template names, which makes it easy to handle even complicated sets of templates without worrying about name collisions.
To make this all work, we need our asset compiler to do something like the Handlebars precompile script, but running inside rhino as in the standard play asset compilers, and modified to work with the customized version of Handlebars that is embedded in Ember. This requires that we set up the rhino js context so that Ember will run (inspired by this gist), then load the ember library, and finally create our own precompile function to convert the template function objects created by ember to strings. We concatenate these and wrap them with some boilerplate that will add the compiled templates to Ember’s
TEMPLATE cache at runtime.
Here’s the code:
We just drop
EmberCompiler.scala into the
project/ directory in our app, make the necessary modification to our
Build.scala script, and play’s build system will pick everything up and start compiling our templates (if you’re already in a play shell you’ll have to tell play to
reload to pick up the changes to the build definition). It’s that simple.
We’re looking for excellent engineers to join our team here at NetWallet. So if you are passionate about doing great things with technology, drop us a line. And, if you’re interested in learning more about the technologies we’re using, come to our talks at Silicon Valley CodeCamp on Play and Ember.