Introducing the template engine

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

In the engine, I have no idea about the tags that will be in the template, and those that will not.

I am currently repeating (foreach) on dictionnary, analyzing my string that I entered in the line builder, and replacing the tags in the template with their corresponding value.

Is there a more efficient / convenient way to do this? I know that the main drawback here is that the string constructor is parsed completely every time for each tag, which is pretty bad ...

(I also check, although not included in the sample, after the process, when my template no longer contains a tag. All of them are formed identically: @@ 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();

Answers:

@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");

: " value2"

: " @@foobar @@text value2"

+3
3

MatchEvaluator? :

string template = "Some @@Foo@@ text in a @@Bar@@ template";
StringDictionary data = new StringDictionary();
data.Add("foo", "random");
data.Add("bar", "regex");
string result = Regex.Replace(template, @"@@([^@]+)@@", delegate(Match match)
{
    string key = match.Groups[1].Value;
    return data[key];
});
+1

, :

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        var template = " @@3@@  @@2@@ @@__@@ @@Test ZZ@@";
        var replacement = new Dictionary<string, string> {
                {"1", "Value 1"},
                {"2", "Value 2"},
                {"Test ZZ", "Value 3"},
            };
        var r = new Regex("@@(?<name>.+?)@@");
        var result = r.Replace(template, m => {
            var key = m.Groups["name"].Value;
            string val;
            if (replacement.TryGetValue(key, out val))
                return val;
            else
                return m.Value;
        });
        Console.WriteLine(result);
    }
}
0

You can change the implementation of the monophonic string format by accepting your stringdictionary. For example http://github.com/wallymathieu/cscommon/blob/master/library/StringUtils.cs

0
source

Source: https://habr.com/ru/post/1709202/


All Articles