Question

I'm successfully using StringTemplate 4 to do some code generation in Visual Studio. I've installed the extensions for StringTemplate and ANTLR and they are really great.

In testing, I can figure out how to use a *.st4 (StringTemplate) file, but how to use the *.stg (StringTemplateGroup) file escapes me. Is it a collection of definitions that can be embedded into another StringTemplate? If so, what would the code look like that would generate from a *.stg rather than a *.st4?

Was it helpful?

Solution

A StringTemplate group file is a collection of templates stored within a single file. The ANTLR project on GitHub contains many examples; e.g. Java.stg which contains all of the code generation templates for the Java target for ANTLR 4.

You can find several examples for using StringTemplate 3 in C# in the StringTemplateTests.cs file from the StringTemplate C# project itself. It's not the most friendly documentation, but it does include examples covering a wide range of ST3 features. Here is one example using StringTemplateGroup:

string templates =
        "group dork;" + newline +
        "" + newline +
        "test(name) ::= <<" +
        "<(name)()>" + newline +
        ">>" + newline +
        "first() ::= \"the first\"" + newline +
        "second() ::= \"the second\"" + newline
        ;
StringTemplateGroup group =
        new StringTemplateGroup( new StringReader( templates ) );
StringTemplate f = group.GetInstanceOf( "test" );
f.SetAttribute( "name", "first" );
string expecting = "the first";
Assert.AreEqual( expecting, f.ToString() );

So it's easier to read, the template group file code into that test looks like this without the escape characters.

group dork;

test(name) ::= <<<(name)()>
>>
first() ::= "the first"
second() ::= "the second"

OTHER TIPS

I'm going to answer my own question here to add to what Sam put up. I think my confusion was because of the vast differences in naming conventions and method calling conventions between ST3 and ST4. Following is a translation of what Sam put up, using ST4

var sr = new StreamReader( "dork.stg" );
var txt = sr.ReadToEnd();
sr.Close();
TemplateGroup group = new TemplateGroupString( txt );
var f = group.GetInstanceOf( "test" );
f.Add( "name", "first" );

// writes out "the first"
Console.WriteLine( f.Render() );

Please let me know if I missed anything, Sam. Thanks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top