Dashboard > StringTemplate > ... > Tutorials > simple_group_example
  StringTemplate Log In | Sign Up   View a printable version of the current page.  
  simple_group_example
Added by Caleb, last edited by Caleb on Oct 19, 2006  (view change)
Labels: 
(None)

This quick example will illustrate how to use string groups. So that you can be up and running as quick as possible. 

Create the string tempate group file called te.stg as below. .stg is an extension commonly used for files of string template groups.

group groupName;

typeInitMap ::= [
   "Integer":  "0",
    "long":    "1",
    default:   "null"
]
variable(type,name) ::= <<
   <b>$type$</b> $name$ = $typeInitMap.(type)$;$\n$
>>

A simple java program to use this template group would look as follows:

import java.io.File;
import java.io.FileReader;

import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.antlr.stringtemplate.language.DefaultTemplateLexer;

public class t {
    /* Quick and very nasty example: */
    public static void main(String[] args)
       throws Exception
    {
        File templateFileName = new File("te.stg");
        StringTemplateGroup group = new StringTemplateGroup(
                new FileReader(templateFileName),
                DefaultTemplateLexer.class    // Leave away if you want to use angle brace notation
            );

        StringTemplate template = group.getInstanceOf("variable");

        template.setAttribute("type", "Integer");
        template.setAttribute("name", "id");

        System.out.println(template.toString());
    }
}

And the output should look as follows:

<b>Integer</b> ID = 0;¶ 

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: 2.5.1 Build:#806 May 06, 2007) - Bug/feature request - Contact Administrators