【问题标题】:perform iteration in StringTemplate4 (C#)在 StringTemplate4 (C#) 中执行迭代
【发布时间】:2013-08-12 18:47:07
【问题描述】:

在 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 似乎没有被填充。有什么想法吗?

【问题讨论】:

  • 你能展示一下TextParseTests.TestModel 的样子吗?具体是构造函数?
  • @kelton52 刚刚添加信息

标签: c# stringtemplate stringtemplate-4


【解决方案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

【讨论】:

  • 成功了,感谢您指出我使用 ST3 备忘单而不是 ST4 的错误!
  • This page 列出了 StringTemplate v3 和 4 之间的区别,引用:现在生成过程中没有隐含的 it 或 attr 属性。帮帮我!
  • 所有这些链接都已损坏或需要 Atlassian 帐户
猜你喜欢
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 2019-07-20
相关资源
最近更新 更多