Dashboard > FreeMarker > Home > Jython
FreeMarker Log In   View a printable version of the current page.
Jython
Added by Jonathan Revusky, last edited by Jonathan Revusky on Feb 20, 2006

Jython is the scripting language Python implemented in pure Java. Jython can be useful in Java projects as a rapid prototyping tool. Also, by embedding a jython interpreter in java applications, one can offer a user-friendly way of scripting underlying java objects. Alternatives to Jython include Rhino, Beanshell, and Groovy. Rhino is javascript implemented in java. FreeMarker also offers experimental Rhino support.

The following is a jython script that illustrates using FreeMarker from within Jython.

#! /usr/bin/env jython

import java, sys, freemarker

data = {"first_name" : "Jonathan", "last_name" : "Revusky"}

if len(sys.argv) >=2 :
    filename = sys.argv[1]
    f = java.io.File(filename).canonicalFile
    conf = freemarker.template.Configuration()
    conf.setDirectoryForTemplateLoading(f.parentFile)
    template = conf.getTemplate(filename)
    out = java.io.OutputStreamWriter(java.lang.System.out)
    template.process(data, out)
else :
    print "No template file specified"

The above jython script takes an argument which is the template file to be used. It uses the data variable as the data model. Note that for the above script to work, a freemarker.jar has to be on the CLASSPATH.

To be clear, the above data model, which contains first_name and last_name is a rather silly example. A real-world example would surely be more complex. It would build a much more complex data model by going out and fetching data from a database server or via some other mechanism. It does show that FreeMarker can transparently use a PyDictionary as its data model. In fact, the data model could be some arbitrarily complex tree that contains built-in jython objects such as PySequence and PyDictionary, custom jython objects, java objects, as well as DOM trees resulting from parsing an XML input source.

You could build some very powerful reporting scripts, taking data from various sources and generating reports, using this kind of mechanism.

Another way to use Jython in relation to FreeMarker is to embed a Jython interpreter in a template via a special transform. (Will develop this later)

Site powered by a free Open Source Project / Non-profit License (more) of Confluence - the Enterprise wiki.
Learn more or evaluate Confluence for your organisation.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 1.4.2 Build:#214 Jun 30, 2005) - Bug/feature request - Contact Administrators