模板引擎实现

我目前正在构建这个小模板引擎。 它需要一个包含参数模板的字符串,以及填写模板的“标签,值”字典。

在引擎中,我不知道模板中的标签和不会出现的标签。

我正在迭代(foreach)在dictionnary上,解析我放在字符串构建器中的字符串,并用模板替换相应的值。

这样做有效/方便吗? 我知道这里的主要缺点是每次完全为每个标签解析stringbuilder,这非常糟糕……

(我也在检查,但不包括在样本中,在我的模板不再包含任何标签的过程之后。它们都以相同的方式格式化:@@ tag @@)

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

对策:

@渣:

 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 in value2模板”

正则表达式和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]; }); 

以下是您可以用作起点的示例代码:

 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 { {"1", "Value 1"}, {"2", "Value 2"}, {"Test ZZ", "Value 3"}, }; var r = new Regex("@@(?.+?)@@"); 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); } } 

您可以将单字符串格式实现修改为接受stringdictionary。 例如http://github.com/wallymathieu/cscommon/blob/master/library/StringUtils.cs