Generating HTML using a template from a .NET application

前端 未结 6 616
后悔当初
后悔当初 2021-01-04 20:35

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

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 21:28

    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.

提交回复
热议问题