Monday, May 27, 2013

How Razor Parses Markup and Code?

            The @ symbol is the heart of the Razor syntax, the character that Razor uses to differ- entiate code from markup. The @ symbol marks a point at which the developer intends to switch from markup to code. In simple cases, no additional characters are needed to indicate when the code stops and the markup resumes. Razor’s intelligent parser determines which parts of the template are code and which are markup.
What makes a valid code statement? 
            Razor uses the following algorithm to find the end of a code statement once it reads the @ symbol trigger:
1. Read to the end of a valid identifier (i.e., a C# or VB keyword) or variable name.
2. If the next character is an opening bracket ( ( or [ )… a. Keep parsing until the corresponding closing bracket is located. Nested brack- ets are also tracked to avoid premature closing of a block. b. Loop back to #2.
3. If the next character is a . (period) and precedes a valid identifier, jump to #1.
 4. Complete the code statement and continue processing the rest of the markup. Razor relies on the current language’s syntax to determine the end of a code statement. Razor also attempts to “read forward,” checking if the upcoming content resembles code or markup.
 The specifics depend on the language currently in use (C# or VB).

Here’s a typical Razor snippet:
@foreach(var item in order.Items) 
{   
 <li>@item.Name</li>
}

The first line initializes the loop variables and opens the loop with an opening bracket; the second line renders markup; and the third line contains the closing bracket to end the loop. There is a clear transition between code and markup because the second line begins with an <li> tag that is clearly an HTML element and the third line is clearly the foreach loop’s closing tag. 

No comments:

Post a Comment