NVelocity ASP.NET Examples

I want to use NVelocity in my ASP.NET MVC application, and not as a viewer, just to render some email templates.

However, I cannot have my life make him work. I downloaded it from the castle project and followed the example of http://www.castleproject.org/others/nvelocity/usingit.html#step1

No matter what I try, I seem to be unable to download the template located on my site. This example suggests using an absolute path, which I tried to no avail:

Template t = engine.GetTemplate("/Templates/TestEmail.vm");

So please someone give me two examples. One of the template downloads is in the website directory and, secondly, the parsing of the string variable (since, probably, my templates will be stored in the database).

Thank you so much ben

+3
source share
3 answers

I used this class in one of my past projects:

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();
        }
    }
}

To create an instance of a class NVelocityTemplateRepository, you need to provide the absolute path in which your templates root is located. Then you use relative paths to link to your files vm.

+6
source

I also added the following method of processing the string instead of the template file (say, if you extract the contents of the template from the database):

        public string RenderTemplateContent(string templateContent, IDictionary<string, object> data)
    {
        if (string.IsNullOrEmpty(templateContent))
            throw new ArgumentException("Template content cannot be null", "templateContent");

        var engine = new VelocityEngine();
        engine.Init();

        var context = GetContext(data);

        using (var writer = new StringWriter()) {
            engine.Evaluate(context, writer, "", templateContent);
            return writer.GetStringBuilder().ToString();
        }
    }

And StructureMap is used to initialize the service:

            ForRequestedType<ITemplateService>()
            .TheDefault.Is.ConstructedBy(()=> 
                new NVelocityTemplateService(HttpContext.Current.Server.MapPath("~/Content/Templates/")));
+2
source

TemplateEngine.

This is an abstraction of templates with an implementation of NVelocity, similar to Darin answer , but it should work a little better, since it uses one instance of VelocityEngine (as opposed to initializing one instance for each render) and has additional caching. It also has a couple of other features, such as logging, the NVelocity property, which overrides and loads templates from assembly resources.

+1
source

Source: https://habr.com/ru/post/1737315/


All Articles