Use Twirl in your next project

The Twirl project is the engine used by Play to support the creation of views in our projects. A some time ago, this project was separated from the core of the framework and, nowadays, is possible to use this fantastic template engine in any Scala/Java project.

The only problem is that you have to use SBT in order to have your views being compiled all the time. Thinking about that, @csokol and I have created a new project that allows you to use Twirl in every app, using SBT or not. Basically we created a class which compiles your views and other class that watches every change in the views directory.

If you are using maven, you can use whatever you want, you just need to follow a simple steps. First you have to download our project, for while you need to clone the repo and install locally. After that, you just need to run our class :).

 mvn exec:java -Dexec.mainClass="" -  Dexec.cleanupDaemonThreads=false

Put some views in the source folder src/main/twirl/simple.scala.html, for example:

  @(customer: String)

   <h1>Welcome @customer</h1>

Let’s say you are writing a servlet and want to return some html for the browser. We just need to use the generated class!

   public class TwirlServlet extends HttpServlet {
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Html clientPage = html.simple.apply("client");


Twirl is a powerful template engine and deserves some attention. The Java world needs a new approach to write views, JSP is too old and does not have a good support to a lot of things needed by our views. You already have Freemarker but, at least in my opinion, Twirl and its compiled views is the next step. For example, you can test your view in a simple way, just invoke a method :).

   public void shouldContainsCustomerName(){
      Html clientPage = html.simple.apply("client");

That is it! This was a different post, not completely related with Play, I hope you had enjoyed.

One thought on “Use Twirl in your next project

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s