代码改变世界

Hello, Razor!

2013-09-10 14:58  执着的梦想  阅读(399)  评论(0编辑  收藏  举报

Razor is a template syntax that allows you to combine code and content in a fluid and expressive manner. Though it introduces a few symbols and keywords, Razor is not a new language. Instead, Razor lets you write code using languages you probably already know, such as C# or Visual Basic .Net.

Razor’s learning curve is very short, as it lets you work with you existing skills rather than requiring you to learn an entirely new language. Therefore, if you know how to write HTML and make a .Net API call, you can easily write markup like the following:

<div>This page rendered at @DateTime.Now</div>

which produces output like this:

<div>This page rendered at 12/7/1941 7:38:00 AM</div>

This example begins with a standard HTML tag ( the <div> tag ), followed by a bit of static text. In the midst of all of this is some dynamic text rendered via a call to the .NET System.DateTime object, followed by the closing (</div>) tag.

Razor’s intelligent parser allows developers to be more expressive with their logic and make easier transitions between code and makeup. The more advanced the makeup, the easier it is to see how Razor’s syntax is cleaner and more expressive than the Web Forms syntax. Compare the following scenarios, each one showing the Razor markup and Web Forms markup required to produce the same HTML:

if/else statement using Web Forms syntax

<% if(User.IsAuthentiated){ %>
    <span>Hello, <%= User.UserName %>!</span>
<% } %>
<% else { %>
    <span>Please <%= Html.ActionLink("log in") %></span>
<% } %>

if/else statement using Razor syntax

@if(User.IsAuthenticated) {
    <span>Hello, @User.Username!</span>
} else {
    <span>Please @Html.ActionLink("log in")</span>
}
 
foreach loop using Web Forms syntax
<ul>
<% foreach(var post in blogPosts){ %>
    <li>        
        <a href=”&lt;%= post.Href %&gt;”>            
            <%= post.Title %>       
        </a>   
    </li>
<% } %>
</ul>

 

foreach loop using Razor syntax

<ul>
    @foreach( var post in blogPosts){
        <li>
            <a href="@post.Href">@post.Title</a>
        </li>
}
</ul>

Though the difference between the Web Forms syntax and Razor syntax is only a few characters, those characters make a big difference the readability of the markup! One of the loudest complains from developers attempting to use Web Forms to author dynamic markup is that its “angle-bracket” syntax is so verbose that it can distract from the page’s logic and content. Additionally, because the Web Forms syntax itself so closely resembles HTML markup, it is often diffcult to determine which parts of the template are code and which are markup.

In direct contrast, Razor use minimal market to perform the same tasks, What’s more, Razor’s syntax was deliberately designed to blend in with HTML, not conflict with it.