【发布时间】:2010-12-10 02:27:58
【问题描述】:
我目前正在构建这个小型模板引擎。 它需要一个包含模板的字符串参数,以及一个“标签,值”的字典来填充模板。
在引擎中,我不知道模板中的标签和不会出现的标签。
我目前正在对字典进行迭代(foreach),解析我放在字符串生成器中的字符串,并将模板中的标签替换为相应的值。
有没有更有效/方便的方法来做到这一点? 我知道这里的主要缺点是 stringbuilder 每次都完全针对每个标签进行解析,这非常糟糕......
(我也在检查,虽然没有包含在示例中,但在我的模板不再包含任何标签的过程之后。它们都以相同的方式格式化:@@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();
回应:
@马克:
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 模板中的一些文本”
而不是:“value2 模板中的一些 @@foobar@@ 文本”
【问题讨论】:
-
很好...使用 Dictionary
而不是 StringDictionary,它会为丢失的键引发错误...并不棘手。
标签: c# .net template-engine