Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple templating engine

0.00/5 (No votes)
23 Oct 2013 1  
Using reflection to build a templating engine

Introduction 

A simple micro templating engine that uses data objects and reflection to effectively populate a template.

Background  

On several occasions I have come across the need for a tiny and efficient yet simple templating engine to print reports, articles, snippets etc within larger systems where a full blown CMS is not warranted. Hence I came up with this solution where you can populate an object and pass it with a template  to a template engine that fleshes out the template. This has worked quite well for me and I would like to share it with any one who has a similar need.

Using the code

The idea behind the templating engine is to use a data object to populate a template. The properties themselves will be markers in the template and the values of these properties will flesh out  the template.

At the heart of the engine is the below method that will use reflection to iterate through the properties and replace the tags/markers in the template.

public string MergeObject(object MergeObject, string tempDoc)
{
    string result = tempDoc;
    Type t = MergeObject.GetType();
    PropertyInfo[] props = t.GetProperties();
    foreach (PropertyInfo prp in props)
    {
        if (MergeObject != null)
        {
           result = Regex.Replace(result, "<"+prp.Name+">", 
                             prp.GetValue(MergeObject, null).ToString());                     
        }
    }
    return result;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here