asp.net - NVelocity ASP.NET 示例

标签 asp.net nvelocity

我希望在 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/

相关文章:

nvelocity - Razor 是否需要 MVC3 或者我只能将它与 .NET 一起使用吗?

c# - 如何捕获 Velocity 中的无效引用错误

html - 忽略格式化 Visual Studio 2010 中的某些部分

c# - 在 c# asp.net 中向多维数组添加一个值

asp.net - 在 ReadAsAsync 方法中读取动态类型

javascript - 什么时候在您的域上使用非 HttpOnly cookie 是合适的?

asp.net - 如何在 ASP.NET 中全局设置日期格式?

caSTLe-monorail - NVelocity,foreach和两个列表的问题

xss - 如何处理 NVelocity 上的 XSS

.net - 如何使用 .NET 创建 JSON 数据?