Chapter 5. The Razor API

Most of this book is dedicated to the Razor syntax and how to use it to interact with the ASP.NET, WebMatrix, and ASP.NET APIs. However, Razor is more than just a syntax; it is backed by a full-fledged API that interprets Razor templates and turns them into executable code (.NET classes) that frameworks such as WebMatrix and ASP.NET MVC can execute to render text.

How Razor Parses Markup and Code provides a brief glimpse at how the Razor parsing logic works, but there is much more that has to happen to turn a document that uses the Razor syntax (“a Razor template”) into rendered HTML. Parsing a Razor template is merely the first step in the process.

Razor Templates: From Markup to .NET Code

Razor templates have a life cycle all their own. Figure 5-1 shows a high-level overview of how Razor templates are used in the course of an application.

The Razor template life cycle

Figure 5-1. The Razor template life cycle

The process of turning Razor markup into .NET code consists of several steps. To illustrate, let’s look at how the Razor parser breaks down the following Razor template:

<div>
   @foreach(var post in Posts) {
      <div>@post.Title</div>
   }
</div>

1. Parse the Razor Template

To begin, the Razor parser analyzes the text (as described in How Razor Parses Markup and Code), breaking it up into “blocks.” Each of these blocks represents a section of the template—either markup or code—and they are hierarchical ...

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.