Creating and running a template file

Gosu template files have the extension .gst. Create template files within the package hierarchy in the file system just as you create Gosu classes. Choose the package hierarchy carefully because you use this package name to access and run your template. The template is a first-class object in the Gosu type system within its package namespace.

In your template file, include the template body with no surrounding quotation marks. The following line is a simple template:

One plus one equals ${ 1 + 1 }.

To create a new template within Studio, in the Project pane within the gsrc section, right-click a package. Next, click New > Gosu Template. In the New Gosu Template dialog, type a meaningful name, and then click OK.

Rendering to a String

To run a template, get a reference to your template and call the renderToString method of the template. The renderToString method returns the template results as a String value.

For example, suppose you create a template file NotifyAdminTemplate.gst within the package mycompany.templates. The fully qualified name of the template is mycompany.templates.NotifyAdminTemplate.

Use the following code to render your template:

var x = mycompany.templates.NotifyAdminTemplate.renderToString()

The variable x contains the String output of your template.

If you need to pass template parameters to your template, provide arguments to the renderToString method.

Rendering to a writer

Optionally, you can render the template directly to a Java writer object. Your writer must be an instance of java.io.Writer. Get a reference to the template and call its render method. Pass the writer as an argument to the render method.

For example, suppose you create a template file NotifyAdminTemplate.gst within the package mycompany.templates. If the variable myWriter contains an instance of java.io.Writer, the following Gosu statement renders the template to the writer:

mycompany.templates.NotifyAdminTemplate.render(myWriter)

If you use template parameters in your template, put your additional parameters after the writer argument.

See also