Creating a Groovy Class
Last modified by Simon Urli on 2023/10/10
Contents
In general, creating a Groovy class in a wiki page is not really recommended and usually it's nicer to create code in Java and make it available to XWiki pages through Script Services.
However there might be a few cases when it's handy to create a Groovy class in a wiki page and reuse it from several other wiki pages.
In XWiki Syntax 2.0+
- Create a page, for example Groovy.HelloWorldClass containing:
{{groovy}} class HelloWorld { String say() { return "Hello World" } } {{/groovy}}
- Use this Groovy class from another wiki page, say from Main.HelloWorldFromGroovy:
{{include document="Groovy.HelloWorldClass"/}} {{groovy}} println new HelloWorld().say() {{/groovy}}
Now when you view Main.HelloWorldFromVelocity you'll see: Hello World
In XWiki Syntax 1.0
You'll need to use the XWiki.parseGroovyFromPage API method. This method allow you to instantiate a Groovy class from both Velocity and Groovy scripts.
- Create a new page, for example Groovy.HelloWorldClass containing:
/* Groovy Class #* */ class HelloWorldClass { def xwiki def context void setObjects(xwiki, context) { setXWiki(xwiki) setContext(context) } void setXWiki(xwiki) { this.xwiki = xwiki } void setContext(context) { this.context = context } String say() { return "Hello World" } } /* *# */
Instantiate and use your class from Velocity
- Create a new page, for example Main.HelloWorldFromVelocity containing:
#set($groovyObject = $xwiki.parseGroovyFromPage("Groovy.HelloWorldClass")) $groovyObject.setObjects($xwiki, $context) $groovyObject.say()
- See the result. Feeling groovy ?
Instantiate and use your class from Groovy
- Create a new page, for example Main.HelloWorldFromGroovy containing:
<% groovyObject = xwiki.parseGroovyFromPage("Groovy.HelloWorldClass") groovyObject.setObjects(xwiki, context) print groovyObject.say() %>