Your existing template scheme is not reliable enough - you should add more special placeholders, for example, for example:
Name:%Name% Age:%age% [if IsEmployed] Employer:%employer% [/if]
You can parse the [if *] blocks using a regular expression (not tested):
Match[] ifblocks = Regex.Match(input, "\\[if ([a-zA-Z0-9]+)\\]([^\\[]*)\\[/if\\]"); foreach(Match m in ifblocks) { string originalBlockText = m.Groups[0]; string propertyToCheck = m.Groups[1]; string templateString = m.Groups[2]; // check the property that corresponds to the keyword, ie "IsEmployed" // if it true, do the normal replacement on the templateString // and then replace the originalBlockText with the "filled" templateString // else, just don't write anything out }
True, although this implementation is full of holes ... Perhaps you will be better off working with template templates, like another answer.
source share