Thursday, March 3, 2016

Handlebars. Helpers

Handlebars easily extensible. Let's create a helper for processing the asset link.  Here is the original Twirl template:
<link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
<script src="@routes.Assets.versioned("javascripts/hello.js")" type="text/javascript"></script>
We need to be able to do @routes.Assets.versioned("...") with the handlebars. Let's create the helper class that will hold all our handlebars helpers. From the start, we will add only one helper, the assets helper. This one could be done even in static method:

package handlebars;

public class Helpers {

  /**
  * Do the same as "@routes.Assets.versioned" in Twirl.
  * 
  * @param url relative path to the asset
  * @return actual path to the asset
  */
  public static CharSequence asset(String url) {
    return controllers.routes.Assets.versioned(new controllers.Assets.Asset(url)).toString();
  }
}
Now we need to register it. Jut one line into the code from my previous post:
...

// Initialize the engine
Handlebars handlebars = new Handlebars(loader);

// Add helpers
handlebars.registerHelpers(Helpers.class);

// Compile the "templates/page.hbs" template
Template template = handlebars.compile("page");

...
Now we can add assets to the handlebars template:
<link rel="stylesheet" media="screen" href="{{asset "stylesheets/main.css"}}">
<link rel="shortcut icon" type="image/png" href="{{asset "images/favicon.png"}}">
<script src="{{asset "javascripts/hello.js"}}" type="text/javascript"></script>
And the result, the same as with Twirl:
<link rel="stylesheet" media="screen" href="/assets/stylesheets/main.css">
<link rel="shortcut icon" type="image/png" href="/assets/images/favicon.png">
<script src="/assets/javascripts/hello.js" type="text/javascript&qu

No comments:

Post a Comment