Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Java Simple Template engine
Branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.


JST - Java Simple Template

JST is a simple template engine which use Java as its programming language and produces Java files to be called anywhere from your code.

Why Yet Another Template Engine ?

Lot’s of template engines try to enforce the MVC pattern (Model View Controller) by limitting the algorithmic features of the language used in the templates. Whereas MVC is definitively a good pattern to avoid writing messy software, the philosophy of JST is to let to the developper the responsability to making the separation of the model and the view, not the template engine.

Unlike some template engine, JST is only targeted to the Java environment. The goal is to have a better integration between a business model and the view. Since both are of the same enviroment, they can shares types, and refactoring can be done more easily.

JST can be compared to JSP. But JST doesn’t need you to run in a J2EE framework, JST is just about plain Java.

It can be also be compared to the template engine from Playframework 2, since a JST template produces a class callable from your code. But JST don’t need a framework, and don’t need scala.

The syntax of JST is quite closed to the Velocity one, because it is a nicely concise syntax. But unlike Velocity, JST is typed and properly scoped, no weird side effect in sight.

Last but not least, JST is based on Xtext. Which means an Eclipse editor is already available for use, with syntax coloring, semantic highlighting, compilation error reporting, refactoring.


  • for(inst; condition; increm): currently for loops can only iterate on Iterable (for(item : list))


  • add a servlet option: the Writer would come from the HttpServletResponse and HttpServletRequest would be available in the template

  • try catch support ? a renderer cannot thow anything else than IOException for now.

Continuous Integration Build


Once generated, the templates need at runtime:

  • commons-lang 2.6

  • guava 10

  • org.eclipse.xtext.xbase.lib 2.4

  • org.hibnet.jst.runtime

Template Language

NB: the programming language is based on Xbase which is not Java but is close to it. For further documentation about that language, see

A quick Tour

The smalest template

Here is the bare minimum you need to have a working template which display Hello World

#main ()
  Hello World
  • #main defines the main rendering function.

  • #end defines when it ends.

A more complete template

package com.acme;

import java.util.List;
import java.text.SimpleDateFormat;
import org.springframework.beans.factory.InitializingBean;

template implements InitializingBean;

Date date = System.currentTimeInMillis();

#main (List<String> names)
    <p>Today is $(new SimpleDateFormat("YYYY/MM/dd").format(date))</p>
    <ul>Hello guys:
        #for(String name : names)
            <li>#call name(name)</li>

#def name(String n)

In this exemple, we have first the package declaration: the package in which the Java classes will generated.

Then the Java-like import, to avoid fully qualifying classes along the template.

template then defines general options on the tempalte and the template Java class hierarchy.

Then there are some fields declared as part of the template class. In this section can also be defined methods.

The #main defines the mandatory entry point of a template. Its parameters will be the parameters of the Java constructor of the template class. Its body defines how it should be rendered.

In the body of the main renderer, $(…​) is outputing the java expression, #for is a loop a java collection, and #call is a call to an inner renderer.

An finally there is the definition of the inner renderer called name.

Outputing expressions

In the outputed content, just use $(aJavaExpression). And to output an empty string rather than null on null values, use $?(aMaybeNullExpression)


#def hello(String name)
  Hello $(name) !

Outputting # or $

Just double the letters: ## and $$


#def account(int account, int amount)
  Account ##$(account) owns $(amount)$$

Escaping and unescaping

When rendering variables into the template, you may want to render your variables in the proper encoding of your generated files. For instance, chevrons should be replaced by < and > in html files. Each expression can be escaped individualy, it overrides the global escaping.

Several encodings are available:

  • XML: use $\xml(…​) or $?\xml(…​)

  • HTML: use $\html(…​) or $?\html(…​)

  • JavaScript: use $\js(…​) or $?\js(…​)

  • Java: use $\java(…​) or $?\java(…​)

  • CSV: use $\csv(…​) or $?\csv(…​)

  • SQL: use $\sql(…​) or $?\sql(…​)

You can also disable the global escaping and output your expression in a raw format. For that, use $\\(…​) or $?\\(…​)


#main (String name, String htmlData, String script)
  Hello $\html(name) !

Default escaping

Rather than escaping each output, every output can be escaped with a default escaping method. This can be set in two ways:

  • the escape method wil be inferred from the JST file name. For instance, mytemplate.html.jst will be default escpaped as html, or mytemplate.js.jst will be default encoded as js.

  • use the template options: at the begining of the template file, declare template with escape = js


To declare variables or just do some Java code, do it within #{…​}


#main (String name)
  #{ var hello = "Hello " + name.trim() + " !" }

Java Imports

At the begining of your template, just do like you would do in plain Java, declares your imports.


import java.util.List;
#main (List list)
  List size is $(list.size())


Loops are like in Java but with the keywords #for, #while or #do, together with #end


import java.util.List
#main (List list)
  #for (item : list)
  #{ var count = 0; }
  #while(count < list.size())
    <li>$(count) : $(list.get(count))</li>
    #{ count = count + 1; }
  #{ var count2 = 0; }
    -- $(count2) : $(list.get(count2))</li>
    #{ count2 = count2 + 1; }
  #end #while(count2 < list.size())


To do branching, just like in Java but with the keywords #if, #else, #elseif and #end.


import java.util.List
#main (List list)
  #if (list == null)
    The list is null
    The list is empty
  #elseif(list.size() == 1)
    The list contains one element
    The list contains $(list.size()) elements


By default the java class generated will be in the default package, ie the root one. You can specify the package in which it will be generated with teh keyword package.


package org.acme;

#main ()
  Hello World

Note that the JST engine doesn’t care about where the jst template is placed. You can place it in a java classpath in a proper package, or just randomly put in some folder. Only the package directive and the name of the file specifies the java class to generate. And actually the jst file is useless at runtime, you don’t need to embed it into your jar, you just need the compiled class of the generated Java file.

An inner renderer

The main renderer is the entry point to render a template. It may be useful to define some other rendering function to be called from the same one, to factorize pieces of the template.

An inner renderer is comparable to a private function of a class. Its definition is like the main but #def is used. Then, Within a renderer, another renderer can be called with the directive #call. The syntax is like a function call in Java.


#main ()
  #call name("World")
#def name(String n)

Template Class

The JST engine will generate a plain Java class named after the template file name. The file name is appended with JstTemplate and the first letter is capitalized to build the name of the generated class. For instance user.jst will generate

Template Class Hierarchy

The generated class can implement some interfaces and extend classes. After declaring the imports, the declaration of the template’s hierachy is like in java but with the keyword template and without the need to name it.


import java.util.ArrayList;

template extends ArrayList implements Serializable;

#def hello()
  Hello World

Abstract Template Class

A template class can also be asbtract. The keyword abstract in front of the keyword template make the class abstract.


abstract template;

#def hello()
  Hello World

Fields and Methods

Fields and methods can be defined on the template class. It is just regular Java.



private File path;

public void setPath(File path) {
  this.path = path;

#def path()

Abstract Renderer

As the template class, a renderer can be declared abstract. Just add the keyword abstract.


abstract template;
#def body(List<String> list)
  #for(i : list)
    <li>#call item(i)</li>
#def abstract item(String i)

Template Options

Options are available to modify globally the rendering methods. They are defined in the header of the template, on the line which defines the template. After the keyword with comes a comma separated list of keys and values.

The supported options are:

  • escape: defines how inline expressions should be escaped by default. Expected value: 'xml', 'html', 'js', 'java', 'csv', or 'sql'.

  • servlet: changes the signature of the rendering method to accept an HttpServletRequest and an HttpServletResponse as parameters. Expected value: true or false.


template with escape = 'html', servlet = true;
#def hello()
  Hello World !

Layout pattern

When working with templates, some are designed to be layouts and some other contents. With JST, no special keyword or contruction is required, just use the Object Oriented patterns: composition and inheritance.

Since the layout should not know about how the actual content should be rendered and vise versa, the interface JstTemplate common to every Jst template will be used. And since it is the layout template which specifies where to put the content, it will be the entry point to render the full page.


  • layout.html.jst

#main (JstTemplate contentTemplate)
    <h1>My website</h1>
    ${ contentTemplate.render(out); }
  • content1.html.jst

#main ()
  <p>Hello World !</p>
  • content2.html.jst

#main (String name)
  <p>Hello $(name) !</p>

public class Main {
  public static void main(String[] args) {
    Content1JstTemplate content1JstTemplate = new Content1JstTemplate();
    LayoutJstTemplate content1 = new LayoutJstTemplate(content1JstTemplate);

    content1.render(new OutputStreamWriter(System.out));

    Content2JstTemplate content2JstTemplate = new Content2JstTemplate("Nico");
    LayoutJstTemplate content2 = new LayoutJstTemplate(content2JstTemplate);

    content2.render(new OutputStreamWriter(System.out));

Integration with Springframework

The template classes could have some injectable resources. The boilerplate code to inject the resources can be generated via an option. If the option factory is set to spring, then an additional Java class will be generated, and will be the class to be managed by springframework and which will generate the template instance as needed, properly injected.

Exemple of mytemplate.jst:

import javax.annotation.Resource;
import javax.sql.DataSource;

template with factory = 'spring';

DataSource datasource;

#main (String name)
  Hello $(name) !

This will generate the additional class MytemplateJstTemplateFactory:

import javax.annotation.Resource;
import org.hibnet.jst.runtime.JstTemplate;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;

public class MytemplateJstTemplateFactory {
  private CommonAnnotationBeanPostProcessor postProcessor;

  public MytemplateJstTemplate build(final String name) {
    MytemplateJstTemplate t = new MytemplateJstTemplate(name);
    postProcessor.postProcessAfterInstantiation(t, t.getClass().getName());
    return t;

Then in your code to render some content, simply do:

MytemplateJstTemplateFactory mytemplateJstTemplateFactory;

public void render(Writer out) {
    MytemplateJstTemplate template ="World");
Something went wrong with that request. Please try again.