Thursday, July 7, 2011

Play framework and jquery template integration

If you have developed any application using Play Framework you will realize that, you can do match without using the play template engine. However, you are likely to get errors if you want to integrate jquery template plugin.

You get those errors usually because, play template engine uses the $ sign to evaluate expressions in the same way that jquery template uses the $ sign to evaluate expressions.

For example, in play you can do this

<h2>${client.name}</h2>
See http://www.playframework.org/documentation/1.2.2/templates#Expressions

Which means you have a render variable called 'client' and you want to prints its 'name' attribute.

This same expression can also be used in jquery template using this template tag. example

<script type='text\html' id='item-template'>
<li>${client.name}</li>
</script>

When you run a play application with this template, the play templating engine will try to evaluate the template and usually you get null pointer exception since such a variable is not available when play templating engine is rendering the file.

This also happens when you are integrating play with knockout.js since it's most useful when integrated with jquery template.

To solve this error, you to have use the #{verbatim} . It escapes all template tags which means they will not be evaluated but render as raw.

So to solve this we have to rewrite our template script to

<script type='text\html' id='item-template'>
<li>#{verbatim}${'${data.name}'}#{/verbatim}</li>
</script>


After play renders our template file the output to the browser will be like the script above. This means, jquery template can then parse it on the client side.

I hope this helps.
Thanks