Razor templates with Tridion 2011 – Getting started

April 25th, 2012 | Posted by Robert Curlette in Tridion

The Tridion Razor Mediator brings all the goodness of the Razor template engine to Tridion.  The Razor mediator uses the official Microsoft Razor Engine and is dependent on .Net 4.0 or higher.  This is good news for us – any improvements in the script engine by Microsoft will be available to us.  Even better, the Razor Mediator is open source; we can see all the code and also update a dependency and recompile if we choose.

The Razor Mediator wraps the Tridion API and provides a more fluent interface to accessing items such as Components and Pages.  Not only that, but many helper functions are also included such as IsFirst, a method to get ComponentPresentations by template name, and super-easy access to Component Link fields and Embedded Fields.  You do not need to know C# or .NET to use it, but if you do then you can use existing .NET methods directly in the templates.  There are many other cool features that I will discuss here in the post.

What is a Mediator

The Tridion Mediator Framework enables developers to create alternative template engines for the Tridion CMS. In Tridion versions 4 and until version 5.2 there was no Mediator framework and we only had Tridion’s built-in “mediator” available and wrote templates in VBScript, JScript, or XSLT. Starting with version 5.3 with the introduction of Compound Templating any developer could create their own template engine, or Mediator, and use this instead of the built-in languages. The first Mediator was an XSLT mediator (for Compound Templating) created by Chris Summers and Yoav Niran. This is still a popular mediator today. However, the new Razor Mediator from Alex Klock promises to provide as much power as XSLT with a lot less sweating involved. 🙂

The Razor Mediator is built on top of the Razor syntax engine from Microsoft, released with ASP.NET MVC, and requries .NET 4.0 and Tridion 2011. If you have done any ASP.NET MVC development then you are familiar with the syntax. The Razor Mediator is not the first external template engine using Microsoft’s Razor engineUmbraco version 5 uses the Razor engine as its’ default template language, replacing the XSLT standard, and has been well received by the community, even by the XSLT die hards.

So, with all that said what are we waiting for?  Let’s dive in and start writing some Razor code.

10 Benefits of Razor Templating:

  • Lots of existing Razor code samples on the web
  • Great Razor Mediator documentation
  • Built on top of the official Microsoft Razor syntax engine. No custom coding or regex matches here! It’s all official! The Mediator is mostly a wrapper around Tridion’s object model with a few helper functions built-in.  Full .NET Framework available in Templates, including functions for Date/Time parsing.
  • Built-in helper functions for iterating over Component Presentations by Template Name (new in 1.2)
  • Smart rendering functionalities like auto-detecting RTF fields and calling ResolveXHTML for us.
  • Easy to access Component Link fields and Embedded Fields – no more looking up the Embedded Field syntax in the reference guide!
  • Logging to the Template Builder ouput window with @Debug(“”)
  • Best template import system of any mediator – can import standard libraries from the config file and not need to include them in each template.  Inline imports allow us to import any type of code – from HTML to CSS, JS, and Razor snippets (imports added in 1.2)
  • Clean syntax calls and requires less code than other mediators.  Less code = less typing = less bugs = happier.
  • Includes its’ own installer – a first for any Tridion Mediator

Getting started with the Tridion Razor Mediator

Getting started is easier than any other Mediator because it comes with its’ own Installer!

1. Download the latest Razor Mediator Installer here (http://code.google.com/p/razor-mediator-4-tridion/downloads/list)
2. Copy installer to the CMS Server
3. Run installer
4. Shut down COM+, restart Publisher

What does the installer do?
– Creates a new Template Building Block Type, Razor Mediator
– Updates the Tridion System.config file at /Tridion/config. If you want to modify the config and add your own default TBB includes this is the place to do it.

Try the new Razor Mediator

– In Tridion, create a new TBB, select Razor as the template language.  If you do not see it here, you may need to re-start your CMS.
– Type some Razor code, save. (ie. <h1>@Component.Title</h1>). Save in a new folder called Razor templates.  VBScript to Razor code samples
– Open Template Builder, create a new Compound Template, type Component Template.
– See if the Folder ‘Razor templates’ is there in the template list of the left. If not, then refresh the template list.
– Add your new Razor template, preview, and witness the magic.

Good news! We’re all ready to begin our small exercise to create a Detail Page using the Razor mediator. I want to highlight the new features from version 1.2, including the GetComponentPresentationsByTemplate, the TBB imports functionality and the IsFirst and IsLast methods.

Microsoft Razor syntax reference:

http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax

Tridion Razor examples:

http://code.google.com/p/razor-mediator-4-tridion/wiki/VBScriptToRazorExamples
Razor helpers and functions
Razor 1.2 new features

I’ll show a few examples of the power and simplicity of the Razor engine highlighting new features from the 1.2 version. I will not cover Tridion dynamic links or navigation since it requires too much logic / detail for this overview.

The Example – A story of on Index page and a Detail page

We will create an Index Page and a Detail page using the Twitter Bootstrap style and HTML.  Our Index page will show 1 Large text banner and a max of 4 intro articles.  Our Detail page will show the article with the Detail Template and also a max of 4 articles in the right-side rail / sidebar.

Detail Page

The detail page will contain 1 news article and a list of related articles in the right sidebar. First we’re going to need HTML before we start coding the template. This is a pre-requisite for any Tridion template and most of the time the template developer is not a front-end HTML developer, and in my case this is also true. Thanks to the Twitter Bootstrap project we have the HTML and CSS done for us – we simply need to fill in some content.

Schema Article Fields:

Heading
Sub-heading
Summary
Body
Links (embedded schema)
Link Title
Link URL External
Link URL Component Link

Source:  Embedded Link Schema
Source:  Detail Schema

Page Template Detail

The Page Template’s primary goal is to write out all the Component Presentations in the right location. It will also include all necessary js and css files, as well as specify a header and meta tags for our page. Page Templates do not write out Component fields. In this example I will only focus on writing out the Component Presentations. Find the location of the Article Component HTML and cut it out – replace with a comment “Article CT Here”. We will do the same for the Sidebar. This leaves us a nice Page Template beginning that we’ll come back to later. Leave the other hard-coded stuff in the HTML file. Later we will replace all content in the HTML page with a Component Presentation or a key/value string. We should never have any hard-coded content in any template – if we do then we have to change the template to update content – something we never want to do.

Tridion Page Template Shell

 

Component Template Detail

The Detail Component Template displays almost all the fields from the Detail page. Notice how we effortlessly display the embedded fields.

Component Template Sidebar

The sidebar template has a special requirement that we need to add a special css class to the first element in the list. For this we’ll use the IsFirst helper method in the Razor Mediator. Other Mediator’s do not have this out of the box.

Index Page

Displays the Article with the ct_banner_text template and up to 4 ct_home_intro Components on the bottom of the screen.

Index Page Templates

Page Template Index

Write the Component Template Code

– Create new Razor TBBs
– Create new TBB. In source tab, first choose the TemplateType of ‘RazorTemplate’. If you forget to do this you will not see it appear in Template Builder since we cannot use VBScritp templates in Compound Templates (default is VBScript in this window).
– Write code in text editor (Notepad++ or VS 2010), copy / paste into the window. Save and close.
– Create new Compound Template in Template Builder, type Component Template. Select the View menu and choose ‘Reload Template Building Blocks. You should now see your new TBB.
– Add TBB. Test with Article.
– Choose File, ‘Close and Open in Content Manager’
– In the ‘Linked Schemas’ tab, Add the appropriate Linked Schema(s). Save and close.
– Save and close. Ready for use on PT now. Copy Component Template name to Page Template ‘GetComponentPresentationsByTemplate’ method.

ct_home_intro


ct_home_banner

Banner Text Template Source

Razor Imports

I have a common <head> section for both templates and would like to re-use the HTML. For this I will use the new Razor Mediator @importRazor(“tbb webdav url”) method.

Configuring the Razor Imports
To use this I need to open the System.config file (from Tridion/config) and in the <razor.mediator node I should add the adminUser attribute:

adminUser=”DOMAIN\Username”

The User account running te COM+ service is usually MTSUser. Make sure this user is an impersonation user in the Tridion MMC snap-in. In my case it was not and I needed to add it. After adding it I shutdown COM+ and it was working fine.

Now it looks like:

<razor.mediator cacheTime=”60″ extractBinaries=”true” adminUser=”Dev2011\curlette”>

Accessing other properties

From Alex, “Every *Model component has a property, .TridionObject, that returns the actual Tridion object (so ComponentModel will return a Component).”
To access the Revisor of a Component we can use:
@Component.TridionObject.Revisor

Better Error Messages

On save it tries to compile your template against the Razor engine. Syntax errors are caught here. Warning- unfortunately the line # does not correspond to the real line #.
When running in Template Builder, any invalid field names are reported as:
“DynamicItemFields: Key ‘subheader’ Not Found In ItemFields”

Much better than the old error “Object or method not found”

Summary

If you are using Tridion 2011 then please give the Razor Mediator a try.  With as little as 1 hour you can run the installer, wrie a sample CT, and experience the simplicity and power of the Mediator.  As you can see the Razor Mediator makes it very easy to write Tridion templates while at the same time using the standard Razor syntax of Microsoft. We handled embedded fields and IsFirst conditions with ease and it is this kind of approach that makes templates faster to write and easier to maintain in the future. We only covered some of the possibilities with the Mediator and did not go into using existing .NET classes in our templates. A big thanks to Alex Klock for creating the Razor Mediator and continuing to add new features to it. I look forward to what is coming next in version 1.3!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *