我希望在 ASP.NET MVC 应用程序中使用 NVelocity,而不是作为 View 引擎,仅用于呈现一些电子邮件模板。
但是,我一生都无法让它发挥作用。我已经从 caSTLe 项目下载了它,并按照 http://www.castleproject.org/others/nvelocity/usingit.html#step1 中的示例进行操作。
无论我如何尝试,我似乎都无法加载位于我的网站中的模板。该示例建议使用绝对路径,我已尝试过但无济于事:
Template t = engine.GetTemplate("/Templates/TestEmail.vm");
请有人给我举两个例子。一是加载位于网站目录中的模板,二是解析字符串变量(因为我的模板可能会存储在数据库中)。
非常感谢 本
最佳答案
我在过去的一个项目中使用过这个类:
public interface ITemplateRepository
{
string RenderTemplate(string templateName, IDictionary<string, object> data);
string RenderTemplate(string masterPage, string templateName, IDictionary<string, object> data);
}
public class NVelocityTemplateRepository : ITemplateRepository
{
private readonly string _templatesPath;
public NVelocityTemplateRepository(string templatesPath)
{
_templatesPath = templatesPath;
}
public string RenderTemplate(string templateName, IDictionary<string, object> data)
{
return RenderTemplate(null, templateName, data);
}
public string RenderTemplate(string masterPage, string templateName, IDictionary<string, object> data)
{
if (string.IsNullOrEmpty(templateName))
{
throw new ArgumentException("The \"templateName\" parameter must be specified", "templateName");
}
var name = !string.IsNullOrEmpty(masterPage)
? masterPage : templateName;
var engine = new VelocityEngine();
var props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, _templatesPath);
engine.Init(props);
var template = engine.GetTemplate(name);
template.Encoding = Encoding.UTF8.BodyName;
var context = new VelocityContext();
var templateData = data ?? new Dictionary<string, object>();
foreach (var key in templateData.Keys)
{
context.Put(key, templateData[key]);
}
if (!string.IsNullOrEmpty(masterPage))
{
context.Put("childContent", templateName);
}
using (var writer = new StringWriter())
{
engine.MergeTemplate(name, context, writer);
return writer.GetStringBuilder().ToString();
}
}
}
为了实例化NVelocityTemplateRepository
您需要提供模板根目录所在的绝对路径。然后你使用相对路径来引用你的 vm
文件。
关于asp.net - NVelocity ASP.NET 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2461704/