Razor support in Umbraco

Important Note!!!

This post was written for Umbraco 4.6.1. Now new version 4.7 is available and there are certain notable changes in terms of Razor in Umbraco 4.7. Please refer to my another post “Razor support in Umbraco 4.7” for changes and new features in Umbraco 4.7

On Jan 12, 2011, Umbraco team released new version 4.6.1 for Umbraco CMS engine and one of the great feature they added was the support for Razor syntax.  Yes, Umbraco now supports Razor syntax. And for those guys, including me, who dislike XSLTs, this is a great alternate for them.  Now we can write the logic in C# rather then in XSLT. Thanks Umbraco Team!!!.

Razor is tbe view engine introduced by Microsoft team with ASP.Net MVC 3.0. It is optimized around HTML generation using a code-focused templating approach. To know more about Razor, following links may be useful:

With Umbraco 4.6, developers can use Razor syntax in Umbraco components. So now Umbraco CMS engine allows Razor scripts to be used in the same way we have been using Iron* languages, XSLT or .NET controls... as a macro. This means that you can use Razor just as you would any other language option. In short, now we can write razor scripts and associate them with Macros.

 

Creating Razor scripts in Umbraco

These script files will have extension ".razor" and by default will live in /python folder besides Iron* files. Razor scripts can be created just like you create any other DLR script file in the Umbraco back office. Razor1

  • Go to "Developers" section

 

  • Right click at "Scripting Files", select "Create"

 

  • In Create dialog box, select language as "Razor by Razor Engine" from the dropdown.
      Razor2 
  • Fill in other fields appropriately and click "Create"   button
  • This will bring up the editor for script.

First Razor For Umbraco : Hello, World!


<div>
  <p>Hello, World!</p>
  <p>Current Page: @Model.Name<p>
  <p>@Model.bodyText</p>
</div>

[Assuming  "bodyText" is a property in associated document type.]

Rest is simple, as usual, create an Macor and associate it with the above created script file.
image    

Model object


Just like Iron* scripts, Razor scripts also have a "Model"    object available in them which is equivelent to the "currentPage" parameter available in XSLT. Its of the type umbraco.MacroEngines.DynamicNode and can be used in the script to access currentPage node and data associated with it.

Important Links:

2 comments

  1. Hi Pinal! Nice Razor samples, they would fit very nice in the http://our.umbraco.org/wiki/reference/code-snippets/razor-snippets collection.
    Kind regards / Jonas

    ReplyDelete
  2. Hi, those two links:
    * Umbraco Razor Syntax for Breadcrumb
    * Canonical Url For Umbraco Using Razor Syntax

    lead to 404 Page not found

    ReplyDelete

Posts a comment

Popular Posts

 
© Old - Pinal Bhatt's Blog
From the desk of Pinal Bhatt | www.PBDesk.com
Back to top