问题描述
奇怪,以前没人问过这个……
Strange, that no one asked this before....
我正在为 4 种语言创建模板化 HTML 电子邮件.我想将 HTML 模板放入我的 .resx 文件中,以便从代码中轻松、国际化地访问它们.像这样:
I am creating templated HTML emails for 4 languages. I want to put the HTML templates into my .resx files to have easy, internationalized access to them from code. Like so:
.resx 文件:
<data name="BodyTemplate" xml:space="preserve">
<value><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<title>Title</title>
...
</body>
</html>
</value>
</data>
但是,很明显,编译器会抱怨 .resx 文件中的 HTML.有没有办法在 .resx 文件中使用 HTML(或 XML).怎么样?
But, obviously, the compiler complains about the HTML inside the .resx file. Is there a way to use HTML (or XML at all) in .resx files. How?
我正在使用 .NET 版本 4 和 dotLiquid 作为模板引擎,如果这很重要的话.
I am using .NET version 4 and dotLiquid as templating Engine, if that matters.
推荐答案
建议:创建你想要的文件,按你想要的方式命名,例如my_template.html"然后将此文件添加到您的项目中.
Suggestion: Create the file you want, name it the way you want, e.g "my_template.html" then add this file to your project.
点击它,然后在属性窗口中选择Build Action"并将其设置为Embedded Resource".
Click on it, then select in the properties window "Build Action" and set it to "Embedded Resource".
当你想访问这个文件时,你可以使用这样的东西(没有正确的使用块:
Whenever you want to access this file, you can use something like this (no with proper using block:
public static string ReadTextResourceFromAssembly(string name)
{
using ( var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( name ) )
{
return new StreamReader( stream ).ReadToEnd();
}
}
根据您的需求量身定制.上面的方法获取资源,假设你把你的资源放在你的项目MyProject
的一个子目录HtmlTemplates"中,命名为my_template.html",那么就可以通过名字来访问了MyProject.HtmlTemplates.my_template.html
Tailor it to your needs. The method above obtains the resource, say you have put your resource in your project MyProject
in a subdirectory "HtmlTemplates and called it "my_template.html", then you can access it by the name
MyProject.HtmlTemplates.my_template.html
然后您可以将其写入文件或直接使用等.
You can then write it out to file or use it directly, etc.
这有一些主要好处:您可以在您的项目中看到您的 html 文件 ,它具有 html 扩展名,因此在 Visual Studio 中编辑它具有语法高亮显示,并且所有工具都应用于 .html 文件.
This has some major benefits: You see your html file in your project, it has the html extension, so editing it in Visual Studio has syntax highlighting and all tools applied to .html files.
我有一堆这样的方法用于我的单元测试,这个将数据提取到一个文件中:
I have a bunch of those methods for my unit tests, this one extracts the data to a file:
public static void WriteResourceToFile(string name, string destination)
{
using ( var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( name ) )
{
if ( stream == null )
{
throw new ArgumentException( string.Format( "Resource '{0}' not found", name), "name" );
}
using ( var fs = new FileStream( destination, FileMode.Create ) )
{
stream.CopyTo( fs );
}
}
}
这篇关于如何将 HTML 代码放入 .resx 资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!