我在使用 Castle NVelocity 时遇到了一个奇怪的问题......
如果模板字符串以 $ 字符结尾,则会引发以下异常:
词法错误:NVelocity.Runtime.Parser.TokenMgrError:第 1 行第 94 列的词法错误。遇到:之后:“”
如果我在字符串的末尾添加一个空格或任何其他字符,它会按预期工作。
有人有解决方法吗?
这是一些重现该问题的示例代码:
class Program
{
static void Main(string[] args)
{
var result = Merge("The quick brown ${Animal} jumps over the lazy dog$", new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("Animal", "fox") });
Console.WriteLine("Success: {0}", result.Key);
Console.WriteLine("Message: {0}", result.Value);
Console.Read();
}
public static KeyValuePair<bool, string> Merge(string template, IList<KeyValuePair<string, string>> data)
{
var ret = new KeyValuePair<bool, string>(false, null);
try
{
if (data != null)
{
var engine = new VelocityEngine();
engine.Init();
var context = new VelocityContext();
foreach (var tokenData in data)
{
context.Put(tokenData.Key, tokenData.Value);
}
var templateContent = template;
var sb = new StringBuilder();
var textWriter = new StringWriter(sb);
engine.Evaluate(context, textWriter, String.Empty, templateContent);
ret = new KeyValuePair<bool, string>(true, sb.ToString());
}
}
catch (Exception ex)
{
ret = new KeyValuePair<bool, string>(false, ex.Message);
}
return ret;
}
}