我使用了代码 here将参数传递给模板文件。
List<string> TopicList = new List<string>();
TopicList.Add("one");
TopicList.Add("two");
TopicList.Add("three");
TopicList.Add("four");
TopicList.Add("five");
PreTextTemplate1 t = new PreTextTemplate1();
t.Session = new Microsoft.VisualStudio.TextTemplating.TextTemplatingSession();
t.Session["TimesToRepeat"] = 5;
foreach (string s in TopicList)
{
t.Session["Name"] = s;
}
t.Initialize();
string resultText = t.TransformText();
但每次,我得到的只是主题列表中的最后一个值(“五”)。
<#@ template language="C#" #>
<#@ parameter type="System.Int32" name="TimesToRepeat" #>
<#@ parameter type="System.String" name="Name" #>
<# for (int i = 0; i < TimesToRepeat; i++) { #>
Line <#= Name #>
<# } #>
Actual Output:Line five
Line five
Line five
Line five
Line five
Expected Output: Line one
Line two
Line three
Line four
Line five
如何才能生成模板中主题列表中的每个值? 就像预期的输出。
很抱歉这个问题的英语和格式很糟糕。
最佳答案
我没有使用过 TextTemplating,所以让我先声明一下我在这里可能不正确。就我通过观察它所看到的而言,您在模板中错误地定义了 Name 。尝试以下操作:
<#@ template language="C#" #>
<#@ parameter type="System.Int32" name="TimesToRepeat" #>
<#@ parameter type="System.Collections.Generic.List<System.String>" name="Names" #>
<# for (int i = 0; i < TimesToRepeat; i++) { #>
Line <#= Names[i] #>
<# } #>
您也可以删除 TimesToRepeat 并改用 foreach:
<#@ template language="C#" #>
<#@ parameter type="System.Collections.Generic.List<System.String>" name="Names" #>
<# foreach (string name in Names) { #>
Line <#= name #>
<# } #>
关于c# - 将列表值传递给 t4 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971069/