C# 使用来自 .NET 应用程序的模板生成 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/897226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating HTML using a template from a .NET application
提问by Mark Heath
I have a .NET console application that needs to generate some HTML files. I could just construct the HTML in a StringBuilder and write the contents out to a file, but I was thinking it would be nicer to use some kind of template file with placeholders for where the data goes and then process my data through it at runtime.
我有一个需要生成一些 HTML 文件的 .NET 控制台应用程序。我可以只在 StringBuilder 中构造 HTML 并将内容写入文件,但我认为使用某种模板文件和占位符来表示数据的位置会更好,然后在运行时通过它处理我的数据。
I'm guessing there are ways to use aspx, or T4, or some of the alternative view engines that you can use with ASP.NET MVC, but I don't know what would be easiest to integrate into a console application (or how I would go about integrating them).
我猜有一些方法可以使用 aspx 或 T4,或者一些可以与 ASP.NET MVC 一起使用的替代视图引擎,但我不知道什么最容易集成到控制台应用程序中(或如何我会去整合它们)。
I want to end up able to call something of the form:
我希望最终能够调用以下形式的内容:
GenerateHtml(htmlPath, template, customDataObject);
采纳答案by Scott Watermasysk
As Matt mentioned, spark is nice but it could be overkill for some simple templates and gets complicated if you are not using it in MVC.
正如马特所提到的,spark 很好,但对于一些简单的模板来说它可能有点矫枉过正,如果你不在 MVC 中使用它,它会变得复杂。
I have personally had a lot of success with NVelocity and I also publish a simple example/wrapper on using it: http://simpable.com/code/simpletemplate/
我个人在 NVelocity 上取得了很多成功,我还发布了一个使用它的简单示例/包装器:http: //simpable.com/code/simpletemplate/
In addition, GraffitiCMS's entire theming system run on NVelocity (although I would have used spark if it were available for this task).
此外,GraffitiCMS 的整个主题系统都在 NVelocity 上运行(尽管如果它可用于此任务,我会使用 spark)。
-Scott
-斯科特
回答by Kev
One way you could do this is create a XSL file as the template, serialise your customDataObject
as XML then perform a transform to generate the required HTML.
您可以这样做的一种方法是创建一个 XSL 文件作为模板,将您的customDataObject
as XML序列化,然后执行转换以生成所需的 HTML。
Update:Whilst I like (and do use) the string replacement method advocated by other folks here, there is a certain flexibility to using XML/XSL. Say your object has a property that is a list, for example an order object with a list of line item objects, you pretty much have to burn into your code the logic that has to render the line items.
更新:虽然我喜欢(并且确实使用)这里其他人提倡的字符串替换方法,但使用 XML/XSL 有一定的灵活性。假设您的对象具有一个列表属性,例如一个带有订单项对象列表的订单对象,您几乎必须将必须呈现订单项的逻辑刻录到您的代码中。
With XSL all you do is pass the serialised order object XML to the XSL and let the XSL handle whatever HTML it needs to generate. This means you can often edit the XSL in place or have variants (order summary, detailed order etc) without adding extra code to your app with all the extra hassle of rebuild/deploy.
使用 XSL,您所做的就是将序列化的订单对象 XML 传递给 XSL,并让 XSL 处理它需要生成的任何 HTML。这意味着您可以经常就地编辑 XSL 或拥有变体(订单摘要、详细订单等),而无需为您的应用程序添加额外的代码,而无需担心重新构建/部署的所有额外麻烦。
But then it all depends on the complexity of what you need to render, for some jobs string replacement is more obvious, for others XSL is the way. As I said, we use both.
但是这一切都取决于您需要呈现的复杂性,对于某些作业字符串替换更明显,对于其他作业 XSL 是方式。正如我所说,我们两者都使用。
回答by Nathan Ridley
Here's some code that illustrates a fairly simple way to accomplish what you're trying to do:
下面的一些代码说明了一种相当简单的方法来完成您要执行的操作:
using System;
using System.IO;
public class HtmlTemplate
{
private string _html;
public HtmlTemplate(string templatePath)
{
using (var reader = new StreamReader(templatePath))
_html = reader.ReadToEnd();
}
public string Render(object values)
{
string output = _html;
foreach (var p in values.GetType().GetProperties())
output = output.Replace("[" + p.Name + "]", (p.GetValue(values, null) as string) ?? string.Empty);
return output;
}
}
public class Program
{
void Main()
{
var template = new HtmlTemplate(@"C:\MyTemplate.txt");
var output = template.Render(new {
TITLE = "My Web Page",
METAKEYWORDS = "Keyword1, Keyword2, Keyword3",
BODY = "Body content goes here",
ETC = "etc"
});
Console.WriteLine(output);
}
}
Using this, all you have to do is create some HTML templates and fill them with replaceable tokens such as [TITLE], [METAKEYWORDS], etc. Then pass in anonymous objects that contain the values to replace the tokens with. You could also replace the value object with a dictionary or something similar.
使用它,您所要做的就是创建一些 HTML 模板并用可替换的标记填充它们,例如 [TITLE]、[METAKEYWORDS] 等。然后传入包含要替换标记的值的匿名对象。您还可以用字典或类似的东西替换值对象。
回答by Rune Grimstad
Another option instead of using XSLT as Kev suggests is to use named string formatting. Using code like this exampleby Phil Haack.
另一个替代 Kev 建议使用 XSLT 的选择是使用命名字符串格式。使用Phil Haack 的示例代码。
Here you can have your template as a string (read from a file maybe) and format it using the given object.
在这里,您可以将模板作为字符串(可能从文件中读取)并使用给定对象对其进行格式化。
Now you could do something like this:
现在你可以做这样的事情:
var person = new { FirstName = "rune", LastName = "grimstad" };
string template = "<html><body><h1>Hello {FirstName} {LastName}</h1></body></html>";
string html = NamedFormat(template, person);
回答by Matt Hinze
Check out docu. It uses the Spark view engine to render templated HTMLfrom a console app. Pretty straightforward.
查看文档。它使用 Spark 视图引擎从控制台应用程序呈现模板化的 HTML。很简单。
回答by Behzad
There are several ways,
有几种方式,
1- Using view engine (Razor, Spark, ...) - this is good if you are using mvc
1- 使用视图引擎 (Razor, Spark, ...) - 如果您使用 mvc,这很好
2- Using XSLT file and transform the given xml to Html
3- Using T4 Text Templates(Best performance, easy to understand)
3-使用 T4 文本模板(最佳性能,易于理解)