1

我成功地使用 StringTemplate 4 在 Visual Studio 中生成了一些代码。我已经安装了 StringTemplate 和 ANTLR 的扩展,它们真的很棒。

在测试中,我可以弄清楚如何使用 *.st4 (StringTemplate) 文件,但是如何使用 *.stg (StringTemplateGroup) 文件让我无法理解。它是可以嵌入到另一个 StringTemplate 中的定义集合吗?如果是这样,从 *.stg 而不是 *.st4 生成的代码会是什么样子?

4

2 回答 2

7

StringTemplate 组文件是存储在单个文件中的模板集合。GitHub 上的 ANTLR 项目包含许多示例;例如Java.stg,其中包含 ANTLR 4 的 Java 目标的所有代码生成模板。

您可以在 StringTemplate C# 项目本身的StringTemplateTests.cs文件中找到几个在 C# 中使用 StringTemplate 3 的示例。它不是最友好的文档,但它确实包含涵盖广泛 ST3 功能的示例。这是一个使用示例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() );

所以更容易阅读,该测试中的模板组文件代码看起来像这样,没有转义字符。

group dork;

test(name) ::= <<<(name)()>
>>
first() ::= "the first"
second() ::= "the second"
于 2013-05-09T22:44:34.383 回答
2

我将在这里回答我自己的问题,以补充 Sam 提出的内容。我认为我的困惑是因为 ST3 和 ST4 之间的命名约定和方法调用约定存在巨大差异。以下是 Sam 使用 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() );

山姆,如果我遗漏了什么,请告诉我。谢谢。

于 2013-05-10T07:13:36.173 回答