template engine implementation

Posted by qwerty on Stack Overflow See other posts from Stack Overflow or by qwerty
Published on 2009-05-27T14:41:33Z Indexed on 2010/03/15 4:09 UTC
Read the original article Hit count: 439

Filed under:
|
|

I am currently building this small template engine. It takes a string containing the template in parameter, and a dictionary of "tags,values" to fill in the template.

In the engine, I have no idea of the tags that will be in the template and the ones that won't.

I am currently iterating (foreach) on the dictionnary, parsing my string that I have put in a string builder, and replacing the tags in the template by their corresponding value.

Is there a more efficient/convenient way of doing this? I know the main drawback here is that the stringbuilder is parsed everytime entirely for each tag, which is quite bad...

(I am also checking, though not included in the sample, after the process that my template does not contain any tag anymore. They are all formated in the same way: @@tag@@)

//Dictionary<string, string> tagsValueCorrespondence;
//string template;

StringBuilder outputBuilder = new StringBuilder(template);
foreach (string tag in tagsValueCorrespondence.Keys)
{
    outputBuilder.Replace(tag, tagsValueCorrespondence[tag]);
}

template = outputBuilder.ToString();

Responses:

@Marc:

string template = "Some @@foobar@@ text in a @@bar@@ template";
StringDictionary data = new StringDictionary();
data.Add("foo", "value1");
data.Add("bar", "value2");
data.Add("foo2bar", "value3");

Output: "Some text in a value2 template"

instead of: "Some @@foobar@@ text in a value2 template"

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET