添加具有以下值的字典:
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)
答案 0 :(得分:2)
这似乎是NVelocity处理.NET Dictionary<K,V>
的缺陷。由于NVelocity在Java支持泛型之前在Velocity中起源,并且因为NVelocity是一个旧代码库,我尝试使用非泛型Hashtable
并且它按预期工作。由于地图未在NVelocity模板中输入,因此切换类应该是一个变化,以解决此缺陷。
随意记录缺陷,但如果没有拉取请求,则不太可能修复。
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.Init();
Hashtable dict = new Hashtable();
dict.Add("customValue1", "mydata");
VelocityContext context = new VelocityContext();
context.Put("dict", dict);
using (StringWriter sw = new StringWriter())
{
velocityEngine.Evaluate(context, sw, "",
"$dict.get_Item('customValue1')\r\n" +
"$dict.get_Item('customValue2')\r\n" +
"$!dict.get_Item('customValue2')"
);
Assert.AreEqual(
"mydata\r\n" +
"$dict.get_Item('customValue2')\r\n" +
"",
sw.ToString());
}