Search code examples
c#.netstringtemplating

What's a good way of doing string templating in .NET?


I need to send email notifications to users and I need to allow the admin to provide a template for the message body (and possibly headers, too).

I'd like something like string.Format that allows me to give named replacement strings, so the template can look like this:

Dear {User},

Your job finished at {FinishTime} and your file is available for download at {FileURL}.

Regards,

-- 
{Signature}

What's the simplest way for me to do that?


Solution

  • Use a templating engine. StringTemplate is one of those, and there are many.

    Example:

    using Antlr.StringTemplate;
    using Antlr.StringTemplate.Language;
     
    StringTemplate hello = new StringTemplate("Hello, $name$", typeof(DefaultTemplateLexer));
    hello.SetAttribute("name", "World");
    Console.Out.WriteLine(hello.ToString());