在这个例子中,我在传入模板之前对代码进行了条带化,我只是想确保我没有错过一些已经内置的 stringtemplate 功能。
使用系统;
使用 System.Linq;
使用 Antlr.StringTemplate;
使用 Microsoft.VisualStudio.TestTools.UnitTesting;
命名空间测试
{
[测试类]
公共类 RandomTests
{
[测试方法]
公共无效 has_a_table()
{
var 用户 = 新 [] {
新{姓氏=“Doe”,名字=“约翰”,年龄=30},
新{姓=“史密斯”,名字=“鲍勃”,年龄=28}
};
var 列 = 新 [] {
新{模板=“$it.LastName$”,头=“姓氏”},
新{模板=“$it.FirstName$”,头部=“名字”}
};
var tableTemplate = @"
<表格>
<头>
<tr>
<th scope=""col"">索引</th>
$columns: { column |<th scope=""col"">$colum n.Head$</th>}$
</tr>
</thead>
<tbody>
$items:{ item |<tr$if(item.Stripe)$ class=""alt""$endif$><td>$i$</td>$item.Item:row()$</tr> }$
</tbody>
</table>
";
var rowTemplate = string.Join
(
"",
(从列中的列
选择
"<td>" + 列.模板 + "</td>"
).ToArray()
);
var templates = new StringTemplateGroup("table-template");
templates.DefineTemplate("table", tableTemplate);
模板.DefineTemplate("行", rowTemplate);
var template = templates.GetInstanceOf("table");
var items = 用户
.Select((item, index) => new { Stripe = index % 2 == 0, Item = item })
.ToArray();
template.SetAttribute("columns", columns);
template.SetAttribute("items", items);
var 实际 = template.ToString();
Assert.IsNotNull(实际);
}