Computer Magic Logo
Hello World

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

Let’s see how to use Razor with Umbraco templates. When we create a new template in Umbraco, the contents of the template looks like the code below.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;
}

In the templates chapters of this tutorial we saw that we can add our HTML at the bottom of the Template but we did not explain what the already inserted code by Umbraco is. The first line defines that our template will inherit from the UmbracoTemplatePate which will supply us with a lot of useful properties and methods. In order to inform ASP.NET MVC that this is a command we inserted the @ character.

The lines 2 to 4 is a code block. This is the syntax that we use when we want to have multiple lines of code. In our example we have only one line which informs the system that we have not defined a Layout for the view. As we saw in the Templates chapter we can use the Layout in order to define which Master Template will be used with this view.

Let’s add one extra line of code in the code block of our view. We will declare a variable called HelloWorld and we will set its value to contain the phrase "Hello World!".

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    string HelloWorld = "Hello World!";
}

Now that we declared a variable we can use it in our HTML in order to display its contents on the browser. We will add a paragraph which will contain the information stored in the HelloWorld variable.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    string HelloWorld = "Hello World!";
}

<p>@HelloWorld</p>

As we said earlier we can use the @ symbol in order to inform the Razor engine that we have a server side statement. The output of the above view is going to be the following.

<p>Hello World!</p>

This causes one small problem. How can we display the @ character on the browser? In order to solve this problem we can use two times the @ character which will inform the Razor engine that we want the @ character to appear on the screen. Below we can see an example of such a case.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    string HelloWorld = "Hello World!";
}

<p>@@@HelloWorld</p>

The output of the code above will be the following.

<p>@Hello World!</p>