15 březen 2013

Since Gaelyk 2.0 is build on the top of Groovy 2.1 branch,
you can use extension modules to add useful methods to particular classes.
As all groovlets and templates are basically scripts,
all of them extend groovy.lang.Script class.
Every method added to groovy.lang.Script will be available in your groovlets and templates as well as other scripts and can be easily used
nearly as easy as Grails tags.

Simple Method

If you create simple extension class like following

Extension class

package cz.orany.vladimir.gaelyk

class GroovyTemplatesExtensions {

    static String helloWorld(Script self) { "Hello World" }
}

and register it in org.codehaus.groovy.runtime.ExtensionModule file in the META-INF/services directory

Extension module descriptor

moduleName=gaelyk-scripts-module
moduleVersion=1.0
extensionClasses= cz.orany.vladimir.gaelyk.GroovyTemplatesExtension
staticExtensionClasses=

you will be able to call the method from your template, e.g. test.gtpl

Example template

<html>
   <head><title>Test hello</title></head>
   <body>${helloWorld()}</body>
</html>

Advanced tag-like method

Of course you can create more sofisticated methods which be close to Grails tags.

Secured 'tag'

<% secured { %>
     <p>This is only visible when the user is signed in</p>
<% } %>

The usage is really simple, the implementation isn't difficult either. You basically write same code as you would write in the template:

Method implementation

static void secured(Script self, Closure body) {
    self.with {
        if(users.userLoggedIn){
            body()
        }
    }
}

The core trick is using the context of current script by calling self.with method. In that case you get simply access to all the bindings available
in the script itself.