我希望在我的ASP.NET MVC应用程序中使用NVelocity,而不是作为视图引擎,只是为了呈现一些电子邮件模板.
但是,我不能为我的生活得到它的工作.我已经从城堡项目下载了它,并按照http://www.castleproject.org/others/nvelocity/usingit.html#step1上的示例进行了操作
无论我尝试什么,我似乎无法加载位于我的网站中的模板.该示例建议使用绝对路径,我试图无效:
Template t = engine.GetTemplate("/Templates/TestEmail.vm");
Run Code Online (Sandbox Code Playgroud)
所以请有人给我两个例子.一个是加载位于网站目录中的模板,另一个是解析一个字符串变量(因为我的模板很可能存储在数据库中).
非常感谢Ben
我在以前的一个项目中使用过这个课程:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了实例化NVelocityTemplateRepository类,您需要提供模板根目录所在的绝对路径.然后使用相对路径来引用vm文件.
| 归档时间: |
|
| 查看次数: |
5543 次 |
| 最近记录: |