Conditional Replacement is used to merge data in an object model with text based templates.
It uses Reflection to read the properties and methods of your data object and recursively merges the data with the template using conditional placeholders, e.g.,
Welcome [Name] to the Code Project. Here the
Name place holder would be replaced with the data in your object on its '
Most IT projects require the production of a formatted version of the data the system is manipulating, whether it be CSV/Excel/Word documents for reports and invoicing, XML for web services, HTML pages for a content management system, etc.
CRep was developed to enable the creation of a variety of text based documents in a structured, re-usable and simple to read manner.
The Demo Project
This contains a simple object model for the RSS feed available on this site. It loads the data into the object model and generates an HTML file from the data and the template provided. You will require the .NET framework 1.1.
Using the code
When creating a
ConditionalReplacement object you are required to pass in the template as a string.
You will then be able to generate your result by calling the
Replace function with your data object.
ConditionalReplacement cRep =
new ConditionalReplacement( "Welcome [Name] to the Code Project" );
string output = cRep.Replace( UserDataObject );
Syntax for Templates
CRep looks for placeholders in the template, these are marked using the following tokens:
|[||Open place holder|
|]||Close place holder|
Simple replacement of placeholders with data; you can access sub object properties using the standard 'dot' notation.
-> Hello Anthony
*N.B. If you find you need to use a token in the template and want CRep to ignore it, just apply the switch '\' before it.
-> Hello [Anthony]
Replacement of placeholders based on the data in the property; you can have as many conditions as you require.
Hello [Person.Forname] ([Person.Forname|=Anthony|great|~|nice] name)
If the person's forename is 'Anthony':
-> Hello Anthony (great name)
-> Hello Sarah (nice name)
You can recurse to sub objects. Think of it as an embedded template using the sub object as its data.
Hello [Person|[Forname] [Surname]]
-> Hello Anthony Johnston
You can recurse the objects in sub collections too. Each object will be subject to the 'embedded template'.
Hello [People@[Person.Forname], ]
-> Hello Anthony, Sarah,
Data can be formatted, this uses the standard
String.Format() method. More details on this method can be found on the Microsoft web site.
Your birth date was [Person.DateOfBirth#d MMM yyyy]
-> Your birth date was 1 Dec 1970
Some may ask why it doesn't use regular expressions, there are three compelling reasons;
- Regular expressions don't handle nested placeholders.
- Regular expressions are difficult to read and understand.
- Regular expressions are slow.