Best way to replace tokens in a large text template

后端 未结 10 1781
我在风中等你
我在风中等你 2020-12-08 17:14

I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use Stri

10条回答
  •  悲&欢浪女
    2020-12-08 17:30

    The only situation in which I've had to do this is sending a templated e-mail. In .NET this is provided out of the box by the MailDefinition class. So this is how you create a templated message:

    MailDefinition md = new MailDefinition();
    md.BodyFileName = pathToTemplate;
    md.From = "test@somedomain.com";
    
    ListDictionary replacements = new ListDictionary();
    replacements.Add("<%To%>", someValue);
    // continue adding replacements
    
    MailMessage msg = md.CreateMailMessage("test@someotherdomain.com", replacements, this);
    

    After this, msg.Body would be created by substituting the values in the template. I guess you can take a look at MailDefinition.CreateMailMessage() with Reflector :). Sorry for being a little off-topic, but if this is your scenario I think it's the easiest way.

提交回复
热议问题