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.
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).
I want to end up able to call something of the form:
GenerateHtml(htmlPath, template, customDataObject);
The <template> tag is used as a container to hold some HTML content hidden from the user when the page loads. The content inside <template> can be rendered later with a JavaScript. You can use the <template> tag if you have some HTML code you want to use over and over again, but not until you ask for it.
The <template> HTML element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript. Think of a template as a content fragment that is being stored for subsequent use in the document.
There are plenty of HTML Template engines/generators.
Just pick any depending on your needs.
Good luck.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With