I have a text template with placehoders that I parse in order to replace placeholders with real values.
Text Template:
Name:%name%
Age:%age%
I use StringBuilder.Replace() to replace placeholders
sb.Replace("%name%", Person.Name);
Now I want to make more advanced algorithm. Some lines of code are conditional. They have to be either removed completely of kept.
Text Template
Name:%Name%
Age:%age%
Employer:%employer%
The line Employer should appear only when person is employed (controlled by boolean variable Person.IsEmployed).
UPDATE: I could use open/close tags. How can find text between string A and B? Can I use Regex? How?
Perhaps you could include the label "Employer:" in the replacement text instead of the template:
Template:
Name:%Name%
Age:%age%
%employer%
Replacement
sb.Replace("%employer%",
string.IsNullOrEmpty(Person.Employer) ? "" : "Employer: " + Person.Employer)
Another alternative might be to use a template engine such as Spark or NVelocity.
See a quick example for Spark here
A full-fledged template engine should give you the most control over the formatted output. For example conditionals and repeating sections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With