添加具有如下值的字典:
Dictionary<string, string> CustomArray = new Dictionary<string, string>();
CustomArray.Add("customValue1", "mydata");
this.velocityContext.Put("array", CustomArray);
像这样使用模板引擎:
Velocity.Init();
string template = FileExtension.GetFileText(templateFilePath);
var sb = new StringBuilder();
using(StringWriter sw = new StringWriter(sb))
{
using(StringReader sr = new StringReader(template))
{
Velocity.Evaluate(
this.velocityContext,
sw,
"test template",
sr);
}
}
return sb.ToString();
在这样的模板中访问:
$array.Get_Item('customValue1')
$array.Get_Item('customValue2')
customValue1 检索得很好,但 customValue2 抛出 KeyNotFoundException 因为字典中不存在该键。如何在不删除引发 KeyNotFoundException 的行的情况下仍生成模板?
我查看了 Apache Velocity 指南,但我不确定如何附加它(https://velocity.apache.org/tools/devel/creatingtools.html#Be_Robust)