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

extensionClasses= cz.orany.vladimir.gaelyk.GroovyTemplatesExtension

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

Example template

   <head><title>Test hello</title></head>

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 {

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.