高效的模板填充 [英] Efficient template population

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

问题描述

假设我有一个文本模板,其中包含许多需要填充的字段:

Say I have a text template with a number of fields that need to be populated:

var template = "hello {$name}. you are {$age} years old. you live in {$location}"

和一个 IDictionary 要替换的值:

and an IDictionary<string,string> of values to substitute:

key     | value
===================
name    | spender
age     | 38
location| UK

填充模板的幼稚方式可能类似于:

The naive way of populating the template might be something like:

var output = template;
foreach(var kvp in templValues)
{
    output = output.Replace(string.format("{{${0}}}", kvp.Key), kvp.Value);
}

然而,这似乎非常低效.有没有更好的办法?

However, this seems painfully inefficient. Is there a better way?

推荐答案

你可以使用 Regex.Replace(),像这样:

You could use a Regex.Replace(), like this:

var output = new Regex(@"\{\$([^}]+)\}").Replace(
    template,
    m => templValues.ContainsKey(m.Captures[1].Value)
        ? templValues[m.Captures[1].Value]
        : m.Value);

AFAIK 如果你的字典是这样构建的,这也可以防止出现意外结果,因为这可能会产生 你好英国.你 38 岁.你住在英国" 以及 你好 {$location}.你今年 38 岁.你住在英国",因为字典不会对它们的键进行排序:

AFAIK this will also prevent unexpected results if your dictionary is built like this, because this might produce "hello UK. you are 38 years old. you live in UK" as well as "hello {$location}. you are 38 years old. you live in UK", since dictionarys don't sort their keys:

key     | value
===================
name    | {$location}
age     | 38
location| UK

当真正需要第一个行为时,您可以多次运行正则表达式.

When the first behavior is actually desired, you can just run the regex multiple times.

如果模板解析实际上是代码的时间关键部分,不要在那里进行模板解析.您应该考虑使用手动解析肖恩推荐的方法.

If the template parsing is actually in a time critical part of the code, don't do the template parsing there. you should consider using the manual parsing method Sean recommended.

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

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