Applying Razor to Text-Based Scenarios

Chapter 5 walks you through the life cycle of a Razor template and how the Razor API converts template text into an executable class. The WebMatrix and ASP.NET MVC frameworks leverage the Razor syntax and the Razor API as a way for developers to define how HTML should be rendered for a web page. However, Chapter 5 shows that it’s relatively straightforward to execute the Razor API outside of WebMatrix or ASP.NET MVC, allowing you to leverage the Razor syntax in your own applications. Not only is it straightforward, but Razor templates can output much more than just HTML, which makes Razor suitable for many templating tasks.

Though Chapter 5 explains everything you need to leverage the Razor API directly, let’s run though an example to show it in action, using Razor templates to drive a theoretical custom email mail merging application. We’ll start with a sample email template and build what we need to turn it into a .NET class that the mail merge application can execute to generate email text:

    Hello, @ServiceRequest.CustomerName!

    Thank you for requesting more information about
    @ServiceRequest.ServiceName on @ServiceRequest.CreateDateDisplayValue.
    Please find the information you requested below
    and we look forward to hearing from you again!

    @ServiceRequest.DetailedInformation

    Sincerely,
    @ServiceRequest.SenderInformation

    [ Information current as of @DateTime.Now ]

Though the custom mail merge application is not an ASP.NET MVC application, creating ...

Get Programming Razor now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.