在StringTemplate4备忘单(http://www.antlr.org/wiki/display/ST/StringTemplate+cheat+sheet)中,它提到执行迭代
<attribute:{anonymous-template}>
Apply an anonymous template to each element of attribute. The iterated `it` attribute is set automatically.
我尝试过以下代码:
List<TextParseTests.TestModel> data = new List<TextParseTests.TestModel>();
for (int i = 0; i < 10; i++)
{
TextParseTests.TestModel model2 = new TextParseTests.TestModel();
model2.Name = i.ToString();
data.Add(model2);
}
string template = @"TestTemplate|| <List:{ [DataList <it.Name>] }> [END]";
Template t = new Template(template);
t.Add("List", data.ToArray());
var result = t.Render();
sb.AppendLine(result);
更新1
以下是TestModel数据结构和相关类。我正在使用这些
public class ContactDetailsTest
{
public string Email { get; set; }
public string Address1 { get; set; }
}
public class TestModel
{
public string Name { get; set; }
public string Surname { get; set; }
public ContactDetailsTest ContactDetails { get; set; }
public TestModel()
{
this.ContactDetails = new ContactDetailsTest();
}
}
然而最终的结果是:
"TestTemplate|| [DataList ] [DataList ] [DataList ] [DataList ] [DataList ] [DataList ] [DataList ] [DataList ] [DataList ] [DataList ] [END]"
它会迭代10次,但变量it
似乎没有被填充。有什么想法吗?
答案 0 :(得分:1)
您需要将模板更改为此
TestTemplate|| <List:{x | [DataList <x.Name>] }> [END]
截至本文档
<attribute:{x | anonymous-template}>
Apply an anonymous template to each element of attribute.
The iterated value is set to argument x.
The anonymous template references <x> to access the iterator value.
您可以将x
设置为您喜欢的任何内容,它只是迭代器的占位符。
问题是您使用的是StringTemplate3备忘单而不是StringTemplate4备忘单http://www.antlr.org/wiki/display/ST4/StringTemplate+cheat+sheet