Wednesday, November 24, 2010

Razor Template Engine

Razor Code can be parsed using Razor template engine. http://razorengine.codeplex.com/
Following sample demonstrate how to achieve that.  Both @function and @helper are working.

SIMPLE TEMPLATE
string template = "Hello @Model.Name! Welcome to Razor!";
            string result = Razor.Parse(template, new { Name = "World" });
            MessageBox.Show(result);

@FUNCTION
string template = "@functions{ public static string RenderDiscountedPrice(decimal price){    return \"Buy now for only 10 with $1.00 off!\";}}  @RenderDiscountedPrice(10);"; // WORKS
            string result = Razor.Parse(template,null);
            MessageBox.Show(result);

@HELPER
string template = "@helper RenderDiscountedPrice(decimal price){ \"Buy now for only 10 with $1.00 off!\";} Hello @RenderDiscountedPrice(10);"; // WORKS
            string result = Razor.Parse(template,null);
            MessageBox.Show(result);

MODEL
string template = "Users List :\n @foreach(var e in Model){\n  @e.Name  @e.Designation  }";       // WORKS
                var f = new FakeEmployeesRepository();
                string result = Razor.Parse(template, f.Employees);
                MessageBox.Show(result);


Where Employees Model is as follows;
public class Employee
       {
              public int EmployeeCode { get; set; }
              public string Name { get; set; }
              public string Designation { get; set; }
       }

public class FakeEmployeesRepository : IEmployeesRepository
       {
              // Hard Coded list of employees
              private static readonly IQueryable<Employee> _fakeEmployees = new List<Employee> {
        new Employee {EmployeeCode=1,  Name = "Imran", Designation="Senior Software Engineer"},
        new Employee {EmployeeCode=2,  Name = "Andrew", Designation="Graphic Designer"},
        new Employee {EmployeeCode=3,  Name = "Michael", Designation="Project Manager"},
        new Employee {EmployeeCode=4,  Name = "John", Designation="Database Administrator" },
        new Employee {EmployeeCode=5,  Name = "Robert", Designation="Project Director"}
        }.AsQueryable();

              public IQueryable<Employee> Employees
              {
                     get { return _fakeEmployees; }
              }
       }

No comments:

Post a Comment