[stringtemplate-interest] basic question to template group
Rabea Gransberger
rgransberger at gmx.de
Mon Jul 14 13:55:27 PDT 2008
Dieter Frej schrieb:
> Hi,
>
> what I wanted to do was to put all templates (all in all these are around 5 templates) in one physical file and use this file to generate my output. Following the great number of example on the Internet, I figured that I need a template group to realize my requirement
>
> StringTemplateGroup stGroup = new StringTemplateGroup("mygroup", "C:\\Users\\xyz\\workspace");
> StringTemplate st = stGroup.getInstanceOf("junit");
> st.setAttribute("tests", ts);
> System.out.println(st.toString());
>
> I created the junit.st file and placed in the directory specified in the constructor of the StringTemplateGroup. In my junit.st I want to call another "template method"
>
> junitclass(testheet) ::= <<
>
> public class $tests.name$ {
>
> $m23ethod(rows=tests.rows)$
>
> }
>
> Putting also
>
> m23ethod(rows) ::= <<
> public void test() {
> $rows:{ u |
> $u.inputColumns; separator=", "$
> }$
>
> in junit.st does not working. I get the following exception
>
> Exception in thread "main" java.lang.IllegalArgumentException: Can't find template m23ethod.st; context is [junit]; group hierarchy is [mygroup]
>
> Maybe I do not fully get template groups, but why am I required to create a separate template for each method I am calling? Or am I doing something wrong? (or totally missing the point? also possible ;-)
You've mixed up the possiblities to create StringTemplate Groups:
- You may group .st files in a directory
- You may create a group file (.stg) which contains all the templates.
Here's an example:
public class GroupFiles {
public static void main(String[] args) throws IOException {
StringTemplateGroup groupDir = new StringTemplateGroup("theGroup",
"templates/group");
final StringTemplate oneTemplate = groupDir.getInstanceOf("one");
oneTemplate.setAttribute("class", GroupFiles.class);
System.out.println(oneTemplate.toString());
final FileReader reader = new FileReader("templates/group.stg");
StringTemplateGroup groupFile = new StringTemplateGroup(reader);
reader.close();
final StringTemplate oneTemplate2 = groupFile.getInstanceOf("one");
oneTemplate2.setAttribute("class", GroupFiles.class);
System.out.println(oneTemplate2.toString());
}
}
Using the following directory structure:
templates
-group
-- one.st
-- two.st
- group.stg
Contents of the files:
one.st:
------
$two(className=class.name)$
------
two.st:
------
$className$
------
group.stg:
-------
group theGroup;
one(class) ::= <<
<two(className=class.name)>
>>
two(className) ::= <<
<className>
>>
--------
Hope this made it a bit clearer.
Rabea
More information about the stringtemplate-interest
mailing list