模板引擎实现 [英] template engine implementation

查看:172
本文介绍了模板引擎实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在建设这个小小的模板引擎。 它使用一个包含参数模板的字符串,而标签,价值观的字典,以填补在模板中。

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.

我目前遍历(的foreach)在dictionnary,我解析字符串,我已经把一个字符串生成器,并通过其相应的值替换标记在模板中。

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.

是否有这样做的更有效的/方便的方法? 我知道这里的​​主要缺点是StringBuilder的解析每次完全是为每个标签,这是相当不错...

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();

对策:

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

输出:的中值2模板某些文本

Output: "Some text in a value2 template"

代替的 的中值2模板有些@@ foobar的@@文

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

推荐答案

怎么样的正则表达式和MatchEvaluator?像这样:

How about a Regex and MatchEvaluator? Like so:

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];
});

这篇关于模板引擎实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆