Skip to content

RazorTemplateEngine

mbsoftlab edited this page Jan 2, 2021 · 5 revisions

Examples for using RazorTemplateEngine implementation

Loading Template from File

Programm.cs

  Person person = new Person
  {
      FirstName = "Jo",
      Emails = new List<string>(){"Jo@doe.de","Jo2@do.de","Jo@do.com"}
  };
  
  ITemplateEngine<Person> templateEngine = new RazorTemplateEngine<Person>();
  templateEngine.LoadTemplateFromFile<Person>("PersonEmailTemplate.cshtml");
  string templateFileContent = templateEngine.CreateStringFromTemplate(person);
  Console.WriteLine();
  Console.WriteLine(templateFileContent);
  
  var htmlFileName = Path.Combine(Path.GetTempPath(), "temp.html");
  File.WriteAllText(htmlFileName, templateFileContent);

Person.cs

namespace TemplateEngineVisualStudioCodeExample
{
    public class Person: TemplateDataModel<Person>
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime Today { get; set; } = DateTime.Now;
        public List<string> Emails { get; set; }
        public bool HasEmails()=>Emails!=null && Emails.Count>0;
    }
}

PersonEmailTemplate.cshtml

@inherits TemplateEngineVisualStudioCodeExample.Person

<p>Hallo @Model.FirstName.</p>

@if(Model.HasEmails())
{
    <p>You have @Model.Emails.Count Emails:</p>
    <ul>
        @foreach (var email in Model.Emails)
        {
            <li>@email</li>
        }
    </ul>
}
else
{
    <p>You have no Emails</p>
}

Datatype compatibility

  • ✔ String
  • ✔ Byte
  • ✔ Short
  • ✔ UShort
  • ✔ Long
  • ✔ ULong
  • ✔ SByte
  • ✔ Char
  • ✔ UInt16
  • ✔ Int32
  • ✔ UInt64
  • ✔ Int16
  • ✔ Int32
  • ✔ Int64
  • ✔ Decimal
  • ✔ Double
  • ✔ DateTime
  • ✔ Boolean
  • ✔ Object
  • ✔ CustomClasses
  • ✔ IList, List, Dictionary, IEnumerable, etc..