h1. Integration Guide

p(note). This section is PlayRythm specific content, pure Rythm user should skip this section

h2. <a name="migrate">Migrate your current project from Groovy template engine to Rythm</a>

PlayRythm is designed to support smooth migrating from Groovy template engine.

PlayRythm hijack the template rendering process if it found the corresponding template exists in the @app/rythm@ folder. Otherwise it quit silently and leave groovy engine to handle it. So what you need to do is just create an new template file using Rythm syntax and put it into the @app/rythm@ folder. Before your new rythm template available your existing groovy template works like a charm, and after the rythm template created, Rythm will take over

p(note). See "Step by step migrate groovy template to rythm":http://software-lgl.blogspot.com.au/2012/05/step-by-step-migrate-your-groovy.html.

h2. <a name="configuration">Configuration</a>

PlayMorphia provides default value for all configuration items, thus enable it to be used with zero configuration.

|*name*|*description*|*default value*|
|@rythm.cache.prodOnly@|Set if cache service enabled only on prod mode. If true then cache service is disabled on dev mode|true|
|@rythm.cache.defaultTTL@|Set default timeout duration in seconds|3600 seconds|
|@rythm.gae@|Set this to true if running in GAE. This will disable bytecode cache in Rythm|false|
|@rythm.noFileWrite@|Same effect as @rythm.gae@|false|
|@rythm.compactOutput@|If true then output content in compact mode, i.e. additonal white space and line breaks will be removed|true in prod mode|

h2. <a name="conflict">Resolve groovy compilation error</a>

-Because groovy template engine does not provide a way to skip parsing any part of the template file, the rythm template file might cause compilation error during precompile process, where rythm has no way to identify some files been a rythm template or groovy template, e.g. some json generation template.-

Start from version 0.9.5 it's suggest to move all rythm templates or at least those compilation error causing templates to @app/rythm@ folder from @app/views@ folder.

Start from version 1.0.0 @app/views@ folder as template root as no longer supported, please move all rythm view files into @app/rythm@ folder. And there will be no groovy compilation error any more caused by rythm template

h2. <a name="customize-template-class">Customize Template Class</a>

Start from v1.0.0-20121103, it allowed developer to customize template class by adding methods and imports to each template class generated by PlayRythm.

h3. Add common imports to all template class

In order to add any arbitrary imports to all templates you can create a file named @__add_on.import@ to @app/rythm@ directory. Inside the file you add the staff needs to be imported one item at a line. For example:

bc. play.modules.aaa.utils.AAA
play.modules.aaa.IAccount
play.modules.aaa.IRole
play.modules.aaa.IRight

After you added the imports, you can use those imported items in any one of your templates:

bc. @extends(main)
<div id="top-bar">
...
<span class="welcome">
Welcome @AAA.me().getName()!
</span>
</div>
@if (AAA.isSuperUser()){
    ...
} else {
    ...
}

h3. Add common methods to all template class

You can add any arbitrary method to all template class by put in them into a file named @__add_on.src@ under @app/rythm@ folder. For example:

bc. // determine if current user has a certain role
protected boolean hasRole(String... roles) {
    return AAA.hasRole(roles);
}
// check if current user is an admin
protected boolean isAdmin() {
    return hasRole("admin");
}
// check if current user is a manager
protected boolean isManager() {
    return hasRole("manager");
}

After you've added the customized methods, you can use them in any template:

bc. @if (isAdmin()) {
    <div class="admin-panel">
    ...
    <div>
} else if (isManager()) {
    <div class="manager-panel">
    ...
    </div>
} else {
    ...
}

h3. <a name="_url">_url methods in template class</a>

Specifically, PlayRythm (start from v1.0.0-20121103) add an new method named @_url()@ to all template class so that you can use reverse url lookup easily in function call:

Example 1: use <code>@url()</code> tag:

bc. $.post('@url(MyController.myAction)', {id: ...}, function(resp){...})

Example 2:  use @_url()@ method in script block:

bc. @{String link = _url(true, "Clients.resetPasswordForm") + "?token=" + token;}

Example 3: use @_url()@ method in tag call:

bc. @def link(String label, String link, boolean showLink) {
    @if(showLink) {<a href="@link">@label</a>}
    else {<span>@label</span>}
}
@section("topactions") {
    @link("Profile", _url("client", client.getId()), !_profile)
    @link("Users", _url("clientUser", client.getId()), !_user)
    @link("Subscription", _url("clientSubscription", client.getId()), !_sub)
}

p(note). There is one difference between passing parameters to <code>@url()</code> tag and @_url()@ method:

Passing parameter to <code>@url()</code> tag:

bc. $.get('@url(Application.myProfile(user.getId()))', function(resp){})

Passing parameter to @_url() method call:

bc. @{String link = _url("Application.myProfile", user.getId())}

h3. <a name="_msg">_msg methods in template class</a>

Specifically, PlayRythm (start from v1.0.0-20121106) add an new method named @_msg()@ to all template class so that you can lookup message files easily in function call:

Example 1: use <code>@msg()</code> tag:

bc. <h1>@msg("application.title")</h1>

Example 2:  use @_msg()@ method in script block:

bc. @{String title = _msg("application.title");}

Example 3: use @_msg()@ method in tag call:

bc. @def link(String label, String link, boolean showLink) {
    @if(showLink) {<a href="@link">@label</a>}
    else {<span>@label</span>}
}
@section("topactions") {
    @link(_msg("client.profile"), _url("client", client.getId()), !_profile)
    @link(_msg("client.user"), _url("clientUser", client.getId()), !_user)
    @link(_msg("client.subscription"), _url("clientSubscription", client.getId()), !_sub)
}

h2. <a name="tag">More about tags</a>

-So far you can keep rythm tags file under @app/views/tags/rythm@ folder. However it is recommened not to use tags folder at all since every rythm template is a tag and can be called from any other rythm templates.-

Start from v1.0.0, @app/views/tags/rythm@ folder as tag root are no longer supported. Please just use @app/rythm@ folder as template root and also the tag root.

E.g. suppose you have a template file @app/views/Order/list.html@, while you can use it as an ordinary template file, you also free to call it as a tag from other rythm template like: <code>@Order.list(myOrders)</code>

h2. <a name="action">Invoking controller actions</a>

PlayRythm 0.9.7 version released with this new feature which is first introduced in Japid template engine and people seems like it a lot. Basically you can invoke a controller action method directly from within the template and fill the place with the render result content. As with any function/tag/template invocation, action method invoke is very straghtforward. Excamples:

bc. @controllers.Applicaiton.index().cache("1h");
@controllers.MyPortal.newsPanel(user);

Things you need to take care of:

# -You must use full qualified method name (including package name, class name) when you invoke controller action method- No longer required since v1.0.0
# You must pass exactly the parameters that matches what is defined in the controller action method signature. The parameter must be passed in by position
# The invocation is directly and will not go through the whole stack of Play's action invocation process. Meaning the <code>@Before</code>, <code>@After</code> and <code>@Final</code> logic will NOT be executed, the same thing happens to all plugin's @beforeActionInvocation()@, @onActionInvocationResult()@ and @afterActionInvocation()@ hooks.
# Start form v1.0 controller invocation is eligible to the following tag invocation extensions:
## "Cache":user_guide#tag_invocation_cache: <code>@controllers.Application.index().cache("1h")</code>
## "Invoke with relative path/import path":user_guide#call_tag_relative_path: <code>@import controllers.*; @Application.index()</code>
## "Assign action result to a variable":user_guide#tag_invocation_assign: <code>@controllers.Application.index().cache("1h").assign("indexPage")</code>. And you can use it as a normal template variable later on: <code>@indexPage.raw()</code>
## "Escape/un-escape render result":user_guide#tag_invocation_escape: <code>@controllers.Application.index().raw()</code>

h2. <a name="cache4">New Cache4 annotation for caching action invocation</a>

Though not so relevant to a template engine, Rythm still provides an new annotation <code>com.greenlaw110.rythm.play.Cache4</code> for controller action (GET and HEAD) result caching. It improves the Play's built-in <code>play.cache.CacheFor</code> in the following way:

* It will check <code>rythm.cache.prodOnly</code> configuration. If it's true (default value), then cache get disabled on dev mode, which is a desired behavior
* You can specify time by configuration name like <code>cron.xx.yy</code>, and Rythm will go @Play.configuration@ to find out the cache time duration. Meaning the cache duration is configurable now. Thus mechanism (by app developer) is well decoupled from policy (by app deployer). Note time duration configuration name must start with "cron"
* You can specify or configure a special time @forever@ and the cache will never expire
* An additional @useSessionData@ attribute allow cache key generation to check the session data, which create a per-user-cache mechanism. This adds an new granularity to the cache system
* It does not cache a @Redirect@ that is not permanent, which enable some modules like *secure* that might trigger a temporary redirect to pass through cache mechanism
* It does not cache @Error@ and @NotFound@ which enable the system to recover from external problems like database error or a network fault.
* Enable cache POST requests when @cachePost@ is set to true. Very useful to deal with certain context like Facebook IFrame tab page

Sample:

bc. @Cache4("cron.top10.cache")
public static void displayTop10() {
...
}

In your @conf/application.conf@:

bc. cron.top10.cache=5mn

<a name="session_data"></a>You can set @useSessionData@ attribute to @true@ to create a per-user-cache mechanism:

bc. @Cache4(useSessionData = true, value="1h")
public static void showMyInterests() {
...
}

<a name="custom_key_provider"></a>Use @key@ parameter if you want to define a customized key provider class:

bc. @Cache4(key = MyCacheKeyProvider.class)
public static void load(String pageId) {
...
}

Where @MyCacheKeyProvider@ could be:

bc. public class MyCacheKeyProvider extends extends ICacheKeyProvider.Default {
    @Override
    public String getKey() {
        return params().get("pageId");
    }
}

p(note). The default key provider returns @"rythm-urlcache:" + request.url + request.querystring@ as the cache key.

<a name="cache_post_request"></a>In certain cases you probably want to cache post requests. For example, facebook always use POST requests when needs to load the tab page inside it's iframe. In this case you can set @cachePost@ to true:

bc. @Cache4(cachePost = true)
public static void loadLandingPage() {
...
}

h3. <a name="cache4_side_effect">Cache4 side effects</a>

@Cache4@ logic is implemented in @RythmPlugin.beforeActionInvocation()@ and @RythmPlugin.onActionInvocationResult()@ hooks. This indicates the following side effects of @Cache4@:

* if the @Result@ get from cache, the all the following logic will get bypassed:
## The @beforeActionInvocation()@ hooks of other plugins (with plugin id > 55)
## All application defined <code>@Before</code> and <code>@After</code> filters
* if the @Result@ is missed in the cache, the all the following logic will get bypassed:
## The @onActionInvocationResult()@ and @afterActionInvocation()@ hook of other plugins (with plugin id > 55)

So you should NOT use @Cache4@ annotation in the following cases:

* Your app or dependent modules have defined controller action filters which will change system state on each request (e.g. system access log)
* Your dependent modules implemented @beforeActionInvocation()@, @afterActionInvocation()@ and @onActionInvocationResult()@ plugin hooks which might change system state on each request
* If you don't know what I am talking about here

p(note). For module or application defined filters that will throw out non-permanent Redirect result, for example, secure module will cause redirect if user has not logged in, in which case you are still safe to use @Cache4@ with @useSessionData@ enabled. See "above example":#session_data.

p(note). <code>@Cache4</code> does not require you to use Rythm template, it works with any controller action methods

h2. <a name="resource">See Also</a>

# %(next)"Rythm Template User guide":user_guide%
# "Reference manual":reference
