我正在成功地使用StringTemplate 4在Visual Studio中执行一些代码生成。我已经安装了StringTemplate和ANTLR的扩展,它们真的很棒。
在测试中,我可以弄清楚如何使用*.st4 (StringTemplate)文件,但我不知道如何使用*.stg (StringTemplateGroup)文件。它是可以嵌入到另一个StringTemplate中的定义的集合吗?如果是这样,那么从*.stg而不是*.st4生成的代码会是什么样子呢?
发布于 2013-05-10 06:44:34
StringTemplate组文件是存储在单个文件中的模板集合。GitHub上的ANTLR项目包含许多示例;例如Java.stg,它包含了ANTLR4的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-10 15:13:36
我将在这里回答我自己的问题,以补充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() );如果我遗漏了什么请告诉我,山姆。谢谢。
https://stackoverflow.com/questions/16472125
复制相似问题