在 .NET 中进行字符串模板化的好方法是什么?
我需要向用户发送电子邮件通知,并且需要允许管理员提供消息正文(也可能还有标题)的模板。
我想要像 string.Format
这样的东西,它允许我提供命名的替换字符串,因此模板可以如下所示:
Dear {User},
Your job finished at {FinishTime} and your file is available for download at {FileURL}.
Regards,
--
{Signature}
对我来说最简单的方法是什么?
I need to send email notifications to users and I need to allow the admin to provide a template for the message body (and possibly headers, too).
I'd like something like string.Format
that allows me to give named replacement strings, so the template can look like this:
Dear {User},
Your job finished at {FinishTime} and your file is available for download at {FileURL}.
Regards,
--
{Signature}
What's the simplest way for me to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
对于那些可以使用新版本 C# 的人来说,这是一个版本:
在一行中 - 现在这是完全支持的语言功能(字符串插值)。
Here is the version for those of you who can use a new version of C#:
In a line - this is now a fully supported language feature (string interpolation).
您可以使用“string.Format”方法:
它允许您将来更改内容并且对本地化友好。
You can use the "string.Format" method:
It allows you to change the content in the future and is friendly for localization.
使用模板引擎。 StringTemplate 就是其中之一,而且还有很多。
例子:
Use a templating engine. StringTemplate is one of those, and there are many.
Example:
我编写了一个非常简单的库 SmartFormat ,它满足您的所有要求。 它专注于编写“自然语言”文本,非常适合从列表生成数据或应用条件逻辑。
语法与
String.Format
极其相似,并且非常简单且易于学习和使用。 以下是文档中的语法示例:该库具有出色的错误处理选项(忽略错误、输出错误、引发错误),并且是开源的且易于扩展,因此您还可以使用其他功能来增强它。
I wrote a pretty simple library, SmartFormat which meets all your requirements. It is focused on composing "natural language" text, and is great for generating data from lists, or applying conditional logic.
The syntax is extremely similar to
String.Format
, and is very simple and easy to learn and use. Here's an example of the syntax from the documentation:The library has great error-handling options (ignore errors, output errors, throw errors) and is open source and easily extensible, so you can also enhance it with additional features too.
基于 Benjamin Gruenbaum 的答案,在 C# 版本 6 中,您可以添加一个带有 $ 的 @,并且几乎可以按原样使用您的代码,例如:
$
用于字符串插值: https://learn.microsoft.com/en-us/dotnet/csharp/ language-reference/tokens/interpolated@
是逐字标识符:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim...您可以使用这些结合起来。
:o)
编辑...
C# 中带有插值和逐字字符串的字符串模板很棒,但如果您想在运行时提供模板,还有另一个选择是这样的:
https://github.com/Handlebars-Net /Handlebars.Net
:o)
Building on Benjamin Gruenbaum's answer, in C# version 6 you can add a @ with the $ and pretty much use your code as it is, e.g.:
The
$
is for string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolatedThe
@
is the verbatim identifier: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim...and you can use these in conjunction.
:o)
Edit...
String templates with interpolation and verbatim strings in C# are great but another option if you want to supply the template at runtime is this:
https://github.com/Handlebars-Net/Handlebars.Net
:o)
一个非常简单的基于正则表达式的解决方案。 支持
\n
样式的单字符转义序列和{Name}
样式的命名变量。源
使用
说明
\n
、\r
、\\
和\{
转义序列和对它们进行硬编码。 您可以轻松添加更多内容或使它们可由消费者定义。RegexOptions.IgnoreCase
标志即可。Regex.Replace
回调末尾返回Match.Value
而不是空字符串。 您也可以抛出异常。{var}
语法,但这可能会干扰本机插值字符串语法。 如果您想在代码中的字符串文字中定义模板,建议将变量分隔符更改为例如%var%
(正则表达式\\.|%([a-z0- 9_.\-]+)%
) 或您选择的更适合用例的其他语法。A very simple regex-based solution. Supports
\n
-style single character escape sequences and{Name}
-style named variables.Source
Usage
Notes
\n
,\r
,\\
and\{
escape sequences and hard-coded them. You could easily add more or make them definable by the consumer.RegexOptions.IgnoreCase
flag.Match.Value
instead of the empty string at the end of theRegex.Replace
callback. You could also throw an exception.{var}
syntax, but this may interfere with the native interpolated string syntax. If you want to define templates in string literals in you code, it might be advisable to change the variable delimiters to e.g.%var%
(regex\\.|%([a-z0-9_.\-]+)%
) or some other syntax of your choosing which is more appropriate to the use case.您可以使用 string.Replace(...),最终在 for-each 中遍历所有关键字。 如果只有几个关键字,您可以将它们放在这样的行中:
或者,如果您需要更强大且有更多选项的东西,您可以使用 Regex.Replace(...)。
阅读这篇有关 codeproject 的文章,查看哪个字符串替换选项最快为你。
You could use string.Replace(...), eventually in a for-each through all the keywords. If there are only a few keywords you can have them on a line like this:
Or you could use Regex.Replace(...), if you need something a bit more powerful and with more options.
Read this article on codeproject to view which string replacement option is fastest for you.
如果有人正在寻找替代方案 - 一个真正的 .NET 方案:
https://github.com/crozone/格式 | https://www.nuget.org/packages/FormatWith
一个很好的简单的可扩展解决方案。 谢谢克罗佐内!
因此,使用 FormatWith 中提供的字符串扩展有两个示例:
它也允许格式化内联替换。 例如,尝试将
emailTemplate
中的{FinishTime}
更改为{FinishTime:HH:mm:ss}
。In case someone is searching for an alternative -- an actual .NET one:
https://github.com/crozone/FormatWith | https://www.nuget.org/packages/FormatWith
A nice simple extendable solution. Thank you crozone!
So using the string extension provided in FormatWith here are two examples:
It allows formatting the replacement inline as well. For example, try changing
{FinishTime}
to{FinishTime:HH:mm:ss}
inemailTemplate
.实际上,您可以使用 XSLT。
您创建一个简单的 XML 模板:
然后创建一个 XmlDocument 来执行转换:
XmlDocument xmlDoc = new XmlDocument();
之后,应用转换:
Actually, you can use XSLT.
You create a simple XML template:
Then create a XmlDocument to perform transformation against:
XmlDocument xmlDoc = new XmlDocument();
After that, apply the transformation:
实现您自己的自定义格式化程序可能是一个好主意。
操作方法如下。 首先,创建一个类型来定义要注入到消息中的内容。 注意:我只会用模板的用户部分来说明这一点...
接下来,实现一个简单的自定义格式化程序...
最后,像这样使用它...
...这将生成文本“亲爱的马丁佩克,你的工作完成了……”
Implementing your own custom formatter might be a good idea.
Here's how you do it. First, create a type that defines the stuff you want to inject into your message. Note: I'm only going to illustrate this with the User part of your template...
Next, implement a simple custom formatter...
Finally, use it like this...
... which will generate the text "Dear Martin Peck. Your job finished...".
如果您需要非常强大的功能(但实际上不是最简单的方法),您可以托管 ASP.NET 并将其用作模板引擎。
您将拥有 ASP.NET 的所有功能来格式化消息正文。
If you need something very powerful (but really not the simplest way) you can host ASP.NET and use it as your templating engine.
You'll have all the power of ASP.NET to format the body of your message.
如果您使用 VB.NET 进行编码,则可以使用 XML 文字。 如果您使用 C# 进行编码,则可以使用 ShatDevelop 将 VB.NET 中的文件与 C# 代码放在同一项目中。
If you are coding in VB.NET you can use XML literals. If you are coding in C# you can use ShartDevelop to have files in VB.NET in the same project as C# code.