May 24, 2012

Step by step migrate your Groovy template to Rythm template - Part Two

In the Step by step migrate your Groovy template to Rythm - Part One I have introduced how to import Rythm module and the overview steps to do the migrate. I have also inspect the Rythm template essentials including expression, flow control, scripting and comment. Now let's take a look at page layout management.

Groovy use #{extends} tag to specify the layout template you want to apply to the current template. On the layout template side, you can use #{doLayout} tag to load the content from sub template. Here is the typical scenario you met on Groovy template:

1. views/Application/index.html:
#{extends "main.html"/}

Home

...

2. views/main.html:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
#{doLayout/}
... </body> </html>

Rythm use pretty much the same thing (@extends and @doLayout tag). Here is what they look like in Rythm:

1. rythm/Application/index.html:
@extends(main)

Home

...

2. rythm/main.html:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
@doLayout()
... </body> </html>

Pretty simple, isn't it? One place worth attention. I use @extends(main) instead of @extends("main.html"). Actually I could use the latter notation, but it is redundant:
  • template inheritance is static, which happen at parsing time, so the quotation mark is redundant
  • template file extension is deduct using the current template format, thus ".html" is redundant
In addition, suppose your layout template are not put into the view root, e.g. you have a layout template file app/views/themes/blueSky/main.html, to reference it in extends tag you do it this way in groovy:
#{extends "themes/blueSky/main.html"/}
In Rythm you can copy the groovy notation:
@extends("themes/blueSky/main.html")
But I recommend you to use the simple Java package notation:
@extends(themes.blueSky.main)
Note, you are free to use relative path and import path shortcuts when you reference the layout template in extends tag, click here to understand relative and import path shortcut.

In addition, @render() is an alias of @doLayout(). They are two identical tags, and it's up to you to decide which one fit your taste.

Now let's see something interesting.

Passing parameter to layout template


So you can pass parameter from content template to layout template via the #set and #get. Let's say you have a layout template main.html:
...
#{doLayout/}
And in your content template, say index.html:
#{extends "main.html"/}
...
#{set theme:"blueSky"/}
...
You can basically follow the same pattern in Rythm. Here is the main.html:
...
@doLayout()
And the content template:
@extends(main)
...
@set(theme:"blueSky")
...
Every thing looks good. However you have more than one way to achieve it in Rythm. Now let's define main.html like the follows:
@args String theme
...
@doLayout()
And the content template changed accordingly:
@extends(main, "blueSky")
...
It's more clean and simple than the clumsy @set and @get, isn't it?

Render sections


So what if you want the content template provides section contents to be inject into different places in the layout template? Groovy templates comes to get/set again. Let's see the main.html in Groovy:
...

#{doLayout/}
...
And the content template:
#{extends "main.html/}
...
#{set "sidebar"}
  • menu-1
  • ...
#{/set} ... #{set "footer"} copyright ... #{/set}
Now let's see how Rythm handle it. First, main.html:
...

@render()
@// as we said before @render() is an alias of @doLayout() ...
And the content template in rythm version:
@extends(main)
...
@section("sidebar") {
  
  • menu-1
  • ...
} ... @section("footer") { copyright ... } ...
So which style do you prefer? No double it's Rythm to me because it's simpler, cleaner, more consistent, and did I mention that Rythm has one feature that's not found in Groovy at all? Let's take a look at the new version of main.html with default content for "footer" section:
...

@render()
@// as we said before @render() is an alias of @doLayout() ...
Now you can omit the footer section from your content template, Rythm will pick up default content automatically!

In this article we introduced the differences and similarity between Groovy and Rythm on template layout management. We see how Rythm use @extends and @doLayout or @render tag to support layout reuse in template authoring. In the next post I am going to introduce you to another powerful feature of Rythm template engine: tags. See you soon!

See also: Step by step migrate your Groovy template to Rythm template - Part One

May 21, 2012

Step by step migrate your Groovy template to Rythm template - Part One

The content of this blog applies to PlayFramework 1.2.x

I've just release Rythm-1.0RC4 with new features including precompile support, null-safe expression and template class properties enhancement, I feel it's time to write this post as there is nearly nothing you can do with Groovy but not with Rythm. Yes you can leverage all your experiences gained from Play's Groovy template engine and apply them immediately to Rythm and gain a 3 to 20 times faster rendering speed with even more clean Razor like syntax.

So first of all, you are safe to do the migration, meaning you keep your system working at all time through out the whole process. Thanks to PlayFramework's rendering process and the plugin architecture, Rythm could implement an unobtrusive template engine plugin to playframework that co-exists with other template engines following the same convention.

To start using Rythm you need to add the following statement into your conf/dependencies.yml file:

    - play -> rythm 1.0.0-RC4 # 1.0.0-RC4 is the current version but you might change it accordingly

And then you go back to your console and type

play deps --sync
mkdir app/rythm

Congratulation! you got Rythm installed and rythm view root folder created, and it's time to take off. And here is what's going to be happened for each of your template files under app/views folder:

step1. copy the file to corresponding folder under app/rythm, e.g.
app/views/main.html -> app/rythm/main.html
app/views/Application/index.html -> app/rythm/Application/index.html

step2. update the file with Rythm syntax. (No worries, we will come back to this point very soon, I promise!)

step3. Type play run and go to your browser press F5 to check the result. You might rewind back to step2 if it needs to adjust here and there, but trust me it's not difficult to do. Once you are okay with this template, move to the next template file and repeat step 1, 2 and 3.

Remember that all the rest part of your entire application works except the template file you are updating. And by the end of each step 3, your whole application works like before. So don't be scared, it's not a big bung migration.

Now let's take our magnifier to inspect what is happening in step 2: update the groovy file with Rythm syntax.

1. Expression


In your groovy template, expressions are enclosed by "${}", E,g.
Hello ${who}

Rythm use "@" sign to mark an expression:
Hello @who

Smart guy will ask how to write the following expression in Rythm:
Jack is a ${vice}maniac.

Ok, here is how it looks like in Rythm:
Jack is a @(vice)maniac.

And similar for compound expressions:
@(foo.bar().numbers[5] + 16)

Note, to output the "@" sign, just put two "@" together:
John

1.1 Null-Safe Expression


I was impressed by the null-safe notation when I first read it and I found it's so handy to use, especially in the form html:
You don't need to say good-bye to null-safe expression, as Rythm brings you the same thing:

1.2 Expression escape


Like Groovy template engine, Rythm automatically escape expressions using html format. As a comparison, Japid won't automatically escape your expressions and require manually invoke the escape function to safely output expression: ${escape(expr)}.

However expression escape is not free, you sacrifice template rendering performance when you escape the expressions. So it's better for you to stop escaping while you are sure that part of your data is safe or you do what to output the HTML code. For a certain expression, use .raw() extension to stop auto-escape:
@html.raw()

If you want to output raw data for all expression in a segment of your template file, use @raw(){...} tag:
@raw() {
   None of the expression outputs will be escaped 
   including the @foo and @bar
}

2. Control flow


Unlike Groovy which use strange tag to expression control flow, Rythm use pure Java style to do it which makes it a compact, expressive, and more Java programmer friendly template language.

2.1 if condition


Groovy template:
#{if user.countryCode == 'en' }
    Connected user is ${user}
#{/if}

Rythm template:
@if ("en".equals(user.countryCode)) {
    Connected user is @user
}

2.2 if-else


Groovy:
#{if user}
    Connected user is ${user}
#{/if}
#{else}
    Please log in
#{/else}

Rythm:
@if(null != user) {
    Connected user is @user
} else {
    Please log in
}

2.3 if-else-if


Groovy:
#{if tasks.size() > 1}
    Busy tasklist
#{/if}
 
#{elseif tasks}
    One task on the list
#{/elseif}
 
#{else}
    Nothing to do
#{/else}

Rythm:
@if(tasks.size() > 1) {
    Busy tasklist
} else if (tasks.size() > 0) {
    One task on the list
} else{
    Nothing to do
}

2.4 loop


Groovy:
    #{list items:products, as:'product'}
  • ${product}
  • #{/list}
Rythm:
    @for(Product product:products) {
  • @product
  • }

All Groovy loop variables are also available in Rythm loop. For the case of the loop above, they are:
  • @product_index, the item’s index, starting at 1
  • @product_isLast, true for the last element
  • @product_isFirst, true for the first element
  • @product_parity, alternates between odd and even

In addition, Rythm provides one additional loop variable to make the parity identification be more convenient:
  • @product_isOdd, true for the odd order element

And to use those variables in your loop:
    @for(Product product:products) { @product_index. @product @(product_isLast ? "" : "-") }

3. Scripting and Comment


Like Groovy, Rythm provides facility to support inline scripting and comments in your template file, the differences is Groovy template engine use Groovy language to script while Rythm use pure Java lanaguage.

3.1 Comment


Groovy:
*{
    this is a block comment in Groovy template engine
}*

*{this is a line comment in Groovy template engine}*

Rythm:
@*
    This is a block comment in Rythm template engnine
*@

@*******************************************
* This is another block comment in Rythm
*******************************************@

@// this is a line comment in Rythm template engine

3.2 Scripting


Groovy use %{...}% and Groovy language to add dynamic logic into template:
%{
   fullName = client.name.toUpperCase()+' '+client.forname;
}%
 

Client ${fullName}


Rythm use @{...} and Java language to do the same work:
@{
   String fullName = client.name.toUpperCase() + " " + client.forname;
}

@****************************************************************
* Note, Groovy language use @{...} to do reverse url lookup, e.g:
* @{Application.index()}
*
* In Rythm you do reverse URL lookup using:
* @url(Application.index())
****************************************************************@

Client @fullName


In this article we briefly introduce how to migrate Groovy template to Rythm template step by step. We also inspected the essential usage of Rythm template including expression, flow control, scripting and comments.

In the next part I will introduce page layout management with @extend keyword, again it achieves all you have in Groovy and more. Stay tuned!

Apr 29, 2012

PlayRythm 1.0.0-RC1 released

Just released this new big version to Play's module repository. There are lots of improvements in terms of both functionality and documentation, several bug fixes and a few break changes:

break changes

  • @renderBody() does not render layout content now. It’s used to render tag body specifically. To render the layout content, use @doLayout() or @render() without section name parameter
  • Automatic escape expression with html format if the template file name suffix is .html. If your code breaks, try to use @raw() tag to surround relevant template part or export your variable with.raw() extension.
    • Note auto-escape can cause template execution performance up to 3 times slower(still much faster than groovy) depending on how many expressions there are in your template, but we consider it a good trade-off to offer a secure default behavior. For those people who “need for speed”, simply wrap your entire template content in raw block:@raw(){your content comes here}.
  • app/view as template root are no longer supported. All rythm template files must be put intoapp/rythm folder
  • app/view/tags/rythm as tag root are no longer supported. Just put tag files as normal template file into app/rythm folder
  • @section tag usage:
    • previously @section sectionName {...}
    • now @section(“sectionName”) {...}

New features

Small enhancements

Issues closed




Apr 4, 2012

Smooth your font in your Java IDE

I have just installed gdipp which makes your windows font rendered like MacOS and it looks really awesome. However I found a tiny problem is the equal symbol "=" is rendered as the minus symbol "-" in my Intellij IDEA, and someone using Netbeans also reported the same issue. So here is the solution based on the issue discussion thread. Add the following section in your gdipp_setting.xml file:
  <process name="idea.*">
   <renderer>20</renderer>
  </process>
So the code means using GetGlyphOutline to render font in process named "idea.*", specifically my IntelliJ IDEA process. Now everything is perfect!

Apr 3, 2012

plupload file browse dialog only open on firefox

I've just experienced an issue with plupload. Say that the file browse dialog open only on Firefox, other browsers doesn't work including IE 9, Chrome, Opera, I didn't test Safari though. Fortunately this thread told me where the issue comes from. You must put the browse_button inside the container:
        var uploader = new plupload.Uploader({
            runtimes : 'html5, flash, browserplus',
            browse_button : 'theUploadBtn', 
            container: 'divPlUploadContainer', // << 'theUploadBtn' must be inside this element!
            max_file_size : '2mb',
            url : 'file/upload/handler',
            multipart: true,
            flash_swf_url : '/lib/plupload/js/plupload.flash.swf',
            filters : [
                {title : "Image files", extensions : "jpg,gif,png"},
            ]
        });
However plupload still not work on Opera with this change

Mar 7, 2012

Rythm - an easy to use high performance Java template engine

I've kept looking for a template engine that has the rich features of Play!framework's groovy template engine, the speed of Japid and the clean, elegant syntax of Razor for years. Without any findings, finally I decide to create one by myself. And it comes Rythm.

I've used it for 2 months in real projects and can't feel any better than that. I'd like to share this work to public and start to promote it. This blog is to give a very brief introduce to Rythm by example. I found Mr. Philipp Schneider's blog on Velocity is easy to go and decide to rewrite it using Rythm. So let's have a look on how I use the template in Java:

Map<string, object> context = new HashMap<string, object>();
context.put("title", "template");
Person p1 = new Person("Mueller");
Person p2 = new Person("Schneider");
List<person> list = new ArrayList<person>();
list.add(p1);
list.add(p2);
context.put("personList", list);

String readyToUseTemplateOutput = Rythm.render("/folderinResource/MyTemplate.anyending", context);

You can also choose to pass template arguments by location:

Person p1 = new Person("Mueller");
Person p2 = new Person("Schneider");
List<person> list = new ArrayList<person>();
list.add(p1);
list.add(p2);

String readyToUseTemplateOutput = Rythm.render("/folderinResource/MyTemplate.anyending", "template", list);

And now the template file:

@args String title, List<person> personList;
Hello world!
This is my first @title
@for (Person person: personList) {
@if (person_index == 1) {Here is a list of persons:}
- @person.getName()
}

The result will look like this:

Hello world!
This is my first template
Here is a list of persons:
- Mueller
- Schneider

So this was really easy to use. And you can also create complex templates, that extends a layout template, invoke customized tags etc. You can do nearly all things that you can in velocity. Maybe even more.

In addition, Rythm is very fast, about 2 to 3 times faster than velocity. Some other features about Rythm:

  • Strong typed. Meaning your template get compiled and less runtime error
  • In-memory compilation. No need to call your javac to process generated java source files. Just call the API to process your template and get your result
  • Cached. Your template compilation get cached so next time no parsing/generating/compilation and it means super fast
  • Hot reload on dev mode. So if you are working on a server program you don't need to restart the server, just hit F5 to refresh your browser.
  • General purpose. Rythm can be used to generate any type of text file. It's not limited to HTML/XML
  • Easy to define tag/macro because every template is a tag and can be invoked from within any other templates
  • Support template inheritance. Reusing your layout page is piece of cake.

Check more on http://www.rythmengine.com!

Updates: I have just release an new template engine plugin built on top of Rythm for Play!Framework