Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Creating, managing, and reusing templates in Umbraco.
Querying and rendering published content.
Querying and rendering media items.
Working with partial views in Umbraco's templates.
Working with partial views macro files.
Working with CSS and JavaScript in Umbraco's templates.
All the code snippets you need to get a jump start on building templates with Razor in Umbraco CMS.
The Razor Cheatsheet is a collection of common methods used for building templates and views in Umbraco CMS.
Get the Umbraco 11 Cheatsheet: https://umbra.co/razorCheatsheet
You can also find the cheatsheet on GitHub where you can give feedback, contribute, or download the template used to generate the sheet.
Use the cheatsheet if you:
Use Models Builder on your project and
Use Umbraco 11.
Most of the methods in the Umbraco 11 version of the cheatsheet will also work in Umbraco 10 and 9.
How to perform common logical tasks in Razor like if/else, foreach loops, switch statements and using the @ character to separate code and markup
Shows how to perform common logical tasks in Razor like if/else, foreach loops, switch statements and using the @ character to separate code and markup.
The @ symbol is used in Razor to initiate code, and tell the compiler where to start interpreting code, instead of returning the content of the file as text. Using a single character for this separation, results in cleaner, compact code which is easier to read.
Commenting your code is important, use comments to explain what the code does. @* *@
indicates a comment, which will not be visible in the rendered output.
If/else statements perform one task if a condition is true, and another if the condition is not true
A foreach loop goes through a collection of items, typically a collection of pages and performs an action for each item
A Switch block is used when testing a large number of conditions
Using named sections in Umbraco
Template sections support the ability to add additional Named Sections to layout templates. These sections can be defined anywhere in the layout file (including within the section of the HTML) and allow you to output dynamic content in your template.
You can define a part of your template as a named section by wrapping it in @section
. This can be rendered in a specific area of the parent of this template, by using @RenderSection
.
For example, you can define the following section within a child template like a Content page:
To define a Named Section, follow these steps:
Go to Settings.
Navigate to a template and click Sections.
Select Define a named section and enter the Section Name.
Click Submit.
Renders a named area of a child template, by inserting a @RenderSection(name)
placeholder. This renders an area of a child template that is wrapped in a corresponding @section [name]
definition.
For example, you can define the following section within a Master template:
To render a Named Section, follow these steps:
Go to Settings.
Navigate to a template and click Sections.
Select Render a named section and enter the Section Name.
[Optional] Select Section is mandatory. This means that the child templates need to have the named section defined for them to work.
Click Submit.
The primary task of any template is to render the values of the current page or the result of a query against the content cache.
Each property in your has an alias, this is used to specify where in the template view to display the value.
You can specify the type of data being returned to help you format the value for display, consider the publish date in our example:
To use the <IHtmlContent>
as the data return type, add the @using Microsoft.AspNetCore.Html;
directive.
The .Value()
method has a number of optional parameters that support scenarios where we want to "fall-back" to some other content.
To use the fallback
type, add the @using Umbraco.Cms.Core.Models.PublishedContent;
directive.
To display a static, default value when a property value is not populated on the current content item:
A second supported method is to traverse up the tree ancestors to try to find a value. If the current content item isn't populated for a property, we can retrieve the value from the parent, grand-parent, or a higher ancestor in the tree. The first ancestor encountered that has a value will be the one returned.
If developing a multi-lingual site and fall-back languages* have been configured, the third method available is to retrieve a value for a different language, if the language we are requesting does not have content populated. In this way, we could render a field containing French content for a property if it's populated in that language, and if not, default to English.
We can also combine these options to create some more sophisticated scenarios. For example, we might want to fall-back via language first, and if that doesn't find any populated content, then try to find a value by traversing through the ancestors of the tree. We can do that using the following syntax, with the order of the fall-back options provided determining the order that content will be attempted to be retrieved:
In this example, we are looking for content firstly on the current node for the default language, and if not found we'll search through the ancestors. If failing to find any populated value from them, we'll use the provided default:
We can use similar overloads when working with ModelsBuilder, for example:
Fall-back languages can be configured via the Languages tree within the Settings section.
Each language can optionally be provided with a fall-back language, that will be used when content is not populated for the language requested and the appropriate overload parameters are provided.
It is possible to chain these language fall-backs, so requesting content for Portuguese, could fall-back to Spanish and then on to English.
You can do this by querying content relative to your current page in template views:
Information on working with partial views in Umbraco
A Partial View (.cshtml
file) is a regular view that can be used multiple times throughout your site. A Partial View is used to break up large markup files into smaller components such as header, footer, navigation menu, etc. It helps to reduce the duplication of code. A partial view renders a view within the parent view.
You can create and edit partial views in the Partial Views folder from the Settings section of the Backoffice.
In the Create menu, there are three options available:
New empty partial view
New partial view from snippet
Folder (for keeping the partial views organized)
To create a partial view, go to the Settings section in the Umbraco backoffice and right-click the Partial Views folder. Choose Create. Select New empty partial view and enter a partial view name and click the Save button. You will now see the partial view markup in the backoffice editor.
By default, the partial view is saved in the Views/Partials
folder in the solution.
To create a partial view from the snippet, go to the Settings section in the Umbraco backoffice and right-click the Partial Views folder. Choose Create. Select New empty partial view from snippet. Select the snippet you want to create a partial view for and enter a partial view name. The code snippet you selected is displayed in the backoffice editor. Click the Save button.
By default, the partial view is saved in the Views/Partials
folder in the solution. Umbraco provides the following partial view snippets:
Empty - Creates an empty partial view file.
Breadcrumb - Creates a breadcrumb of parents using the Ancestors()
method to generate links in an unordered HTML list. It displays the name of the current page without a link.
Edit Profile - Creates a Member profile model that can be edited.
List Ancestors From Current Page - Displays a list of links to the parents of the current page using the Ancestors()
method to generate links in an unordered HTML list. It displays the name of the current page without a link.
List Child Pages From Current Page - Displays a list of links to the children of the current page using the Children()
method to generate links in an unordered HTML list.
List Child Pages Ordered By Date - Displays a list of links to the children of the current page using the Children()
method to generate links in an unordered HTML list. The pages are sorted by the creation date in a descending order using the OrderByDescending()
method.
List Child Pages Ordered By Name - Displays a list of links to the children of the current page using the Children()
method to generate links in an unordered HTML list. The pages are sorted by the page name using the OrderBy()
method.
List Child Pages With DocType - Displays only the children of a certain Document Type.
List Descendants From Current Page - Displays a list of links for every page below the current page in an unordered HTML list.
Login - Displays a login form.
Login Status - Displays the user name if the user is logged in.
Multinode Tree-picker - Lists the items from a Multinode tree picker using the picker's default settings.
Navigation - Displays a list of links of the pages under the top-most page in the Content tree. It also highlights the currently active page/section in the navigation menu.
Register Member - Displays a Member registration form. It will only display the properties marked as Member can edit on the Info tab of the Member Type.
Site Map - Displays a list of links of all the visible pages of the site using the Traverse()
method to select and display the markup and links as nested unordered HTML lists.
To create a folder, go to the Settings section in the Umbraco backoffice and right-click the Partial Views folder. Choose Create. Select Folder. Enter a folder name and click the Create button.
To render the created partial view into any template, use any of these helper methods: @Html.PartialAsync
, @Html.Partial()
, or @Html.RenderPartial()
Information on working with stylesheets and JavaScript in Umbraco, including bundling & minification.
You can create and edit stylesheets in the Stylesheets folder in the Settings section of the Backoffice.
In the Create menu, these options are available:
Stylesheet file (for use in templates/views)
Folder (for keeping stylesheets organized)
It is currently not possible to use any CSS preprocessor (such as Syntactically Awesome Style Sheets (SASS)) in the backoffice.
After creating a new stylesheet, you would work with it as you would with templates or JavaScript files - using the built-in backoffice text editor. When you're working with stylesheets, you also have access to the Rich Text Editor, which allows you to create CSS styles and get a real-time preview.
The rules you create in the Rich Text Editor section will carry over to the Code tab.
To reference your newly included stylesheet in a template file, navigate to Templates, pick the template you like (css files are usually referenced in the layout or home templates) and link to it with the link
tag.
By default, the stylesheets will be saved in the wwwroot/css
folder in the solution. To reference them you can use either of the methods used in the above screenshot.
or
With the stylesheet referenced, you will be able to style the template file with the rules and classes defined in the stylesheet.
If your RTE is styled differently on the frontend of the site, the backoffice styling might be getting overwritten by other stylesheets you have included.
To create and edit JavaScript files in the Backoffice, head on over to the Scripts folder in the Settings section of the Backoffice.
From here you can add a new JavaScript file, or a new folder.
Add a new JavaScript file and write your code:
Then, navigate to the template where you would like to include your JS file.
By default all JavaScript files will be stored in the wwwroot/scripts
folder in the solution.
If you are working locally, you can create CSS and JS files outside of the Backoffice - as long as they are placed in appropriate folders (css
and scripts
), they will show up in the Backoffice when you right-click on the folder and then pick reload.
You can use whichever tool you are comfortable with for bundling & minification by implementing the IRuntimeMinifier
interface in your custom minifier class, though it is worth noting that Umbraco 9+ ships with Smidge which offers lightweight runtime bundling and minification.
You can create various bundles of your site's CSS or JavaScript files in your code that can be rendered later in your views. There can be a single bundle for the entire site, or a common bundle for the files you want to be loaded on every page, as well as page-specific bundles, just by listing your resources in the order you like.
Step 1: Create a INotificationHandler<UmbracoApplicationStartingNotification>
Step 2: Register the INotificationHandler
in the Program.cs
file.
Step 3: Render the bundles by the bundle name in a view template file using the Smidge TagHelper:
The following bundling options can be set when creating your bundles:
The Smidge TagHelper does not consider the value of Umbraco:CMS:Hosting:Debug
set in your appsettings file.
If you do need to debug bundles you can inject hostingSettings
and add the debug
attribute as shown below.
In case you are in Debug mode, your bundles won't be minified or bundled, so you would need to set Umbraco:CMS:Hosting:Debug: false
in your appsettings file.
Templating in Umbraco including inheriting from master template
Templating in Umbraco builds on the concept of Razor Views from ASP.NET MVC - if you already know this, then you are ready to create your first template - if not, this is a quick and handy guide.
By default, all document types should have a template attached - but in case you need an alternative template or a new one, you can create one:
Open the Settings section inside the Umbraco backoffice and right-click the Templates folder. Choose Create. Enter a template name and click the Save button. You will now see the default template markup in the backoffice template editor.
To use a template on a document, you must first allow it on the content's type. Open the Document Type you want to use the template, go to the Templates tab and select the template under the Allowed Templates section.
A template can inherit content from a master template by using the ASP.NET views Layout feature. Let's say we have a template called MasterView, containing the following HTML:
We then create a new template called textpage and in the template editor, click on the Master Template button and set its master template to the template called MasterView:
This changes the Layout
value in the template markup, so textpage looks like this:
When a page using the textpage template renders, the final HTML will be merged replacing the @renderBody()
placeholder, and produce the following:
What's good to know, is that you are not limited to a single section. Template sections allow child templates that inherit the master layout template to insert HTML code up into the main layout template. For example, a child template inserting code into the <head>
tag of the master template.
For instance, if you want to be able to add HTML to your <head>
tags write:
By default, when rendering a named section, the section is not mandatory. To make the section mandatory, add true
or enable Section is mandatory field in the Sections option.
On your child page template call @section Head {}
and then type your markup that will be pushed into the Master Template:
Another way to reuse HTML is to use partial views - which are small reusable views that can be injected into another view.
Like templates, create a partial view, by right-clicking Partial Views and selecting Create. You can then either create an empty partial view or create a partial view from a snippet.
The created partial view can now be injected into any template by using the @Html.Partial()
method like so:
Information on working with partial view macro files in Umbraco
Partial View Macro Files will be removed in the next version. Consider using Partial Views.
A Macro is a reusable piece of functionality with some configuration options in the Backoffice. A Partial View Macro File (.cshtml
file) is a specific file configuration that is associated with the Macro. A Partial View Macro File generates a Macro that can be inserted and rendered in the Grid and Rich Text Editor data types. Additionally, you can define parameter values and enable caching in Macros in the Backoffice. Partial View Macro Files are the recommended macro type to use in Umbraco.
You can create and edit Partial View Macro Files in the Partial View Macro Files folder from the Settings section of the Backoffice.
In the Create menu, there are four options available:
New partial view macro
New partial view macro (without macro)
New partial view macro from snippet
Folder (for keeping the partial view macro files organized)
To create a Partial View Macro File, go to the Settings section in the Umbraco backoffice and right-click the Partial View Macro Files folder. Choose Create. Select New partial view macro and enter a Partial View Macro Filename. Enter the macro logic and click the Save button. You will now see the Partial View Macro File in the Partial View Macro Files folder. You also see the macro in the Macros folder in the Backoffice.
By default, the Partial View Macro File is saved in the Views/MacroPartials
folder.
To create a Partial View Macro File without a macro, go to the Settings section in the Umbraco backoffice. Click right on the Partial View Macro Files folder. Choose Create. Select New partial view macro (without macro) and enter a Partial View Macro Filename. Enter the macro logic and click the Save button. You will now see only the Partial View Macro File in the Partial View Macro Files folder in the Backoffice.
By default, the Partial View Macro File is saved in the Views/MacroPartials
folder.
To create a Partial View Macro File from the snippet, go to the Settings section in the Umbraco backoffice. Click right on the Partial Views Macro Files folder. Choose Create. Select New empty partial view macro from snippet. Select the snippet you want to create a partial view for and enter a Partial View Macro Filename. The code snippet you selected is displayed in the backoffice editor. Click the Save button. You will now see the Partial View Macro File in the Partial View Macro Files folder. You also see the macro in the Macros folder in the Backoffice.
By default, the partial view is saved in the Views/MacroPartials
folder. Umbraco provides the following partial view macro snippets:
Empty - Creates an empty partial view file.
Breadcrumb - Creates a breadcrumb of parents using the Ancestors()
method to generate links in an unordered HTML list. It displays the name of the current page without a link.
Edit Profile - Creates a Member profile model that can be edited.
Gallery - Displays a gallery of images from the Media section. It works with either a 'Single Media Picker' or a 'Multiple Media Picker' macro parameters.
List Ancestors From Current Page - Displays a list of links to the parents of the current page using the Ancestors()
method to generate links in an unordered HTML list. It displays the name of the current page without a link.
List Child Pages From Changeable Source - Lists all the child pages under a specific page in the Content tree.
List Child Pages From Current Page - Displays a list of links to the children of the current page using the Children()
method to generate links in an unordered HTML list.
List Child Pages Ordered By Date - Displays a list of links to the children of the current page using the Children()
method to generate links in an unordered HTML list. The pages are sorted by the creation date in a descending order using the OrderByDescending()
method.
List Child Pages Ordered By Name - Displays a list of links to the children of the current page using the Children()
method to generate links in an unordered HTML list. The pages are sorted by the page name using the OrderBy()
method.
List Child Pages With DocType - Displays only the children of a certain Document Type.
List Descendants From Current Page - Displays a list of links for every page below the current page in an unordered HTML list.
List Images From Media Picker - Displays a series of images from a media folder.
Login - Displays a login form.
Login Status - Displays the user name if the user is logged in.
Multinode Tree-picker - Lists the items from a Multinode tree picker using the picker's default settings.
Navigation - Displays a list of links of the pages under the top-most page in the Content tree. It also highlights the currently active page/section in the navigation menu.
Register Member - Displays a Member registration form. It will only display the properties marked as Member can edit on the Info tab of the Member Type.
Site Map - Displays a list of links of all the visible pages of the site using the Traverse()
method to select and display the markup and links as nested unordered HTML lists.
InsertUmbracoFormWithTheme - If a theme is provided as a macro parameter, Umbraco Forms will use the custom theme files.
RenderUmbracoFormScripts - Renders your Umbraco Forms scripts. In many cases, you might prefer rendering your scripts at the bottom of the page as this generally improves site performance.
To create a folder, go to the Settings section in the Umbraco backoffice and right-click the Partial Views Macro Files folder. Choose Create and select Folder. Enter a folder name and click the Create button.
To render the created Partial View Macro File in any template, use the RenderMacroAsync
method:
To render the content from the Grid, see the article.
In many cases, you want to do more than display values from the current page, like creating a list of pages in the navigation. You can access content relative to the current page using methods such as Children()
, Descendants()
& Ancestors()
. Explore the .
You can use the Query Builder in the template editor to build more advanced queries.
Rich Text Editor stylesheet file (for use in )
Your stylesheets can be used in Rich Text Editors (datatype) as well - please see the documentation for more information.
Smidge with RunTimeMinification setting is scheduled for removal on Umbraco 14. You can install the package separately if needed and read the documentation on how to get started.
See below for the different .
Full details about Smidge can be found here:
You can do this by using . Add named sections to your master template with the following code:
Info on rendering media items and imaging cropping
Templates (Views) can access items in the Media library to assist in displaying rich content like galleries.
In the following examples, we will be looking at rendering an Image
.
Image is only one of the 'types' of Media in Umbraco. The same principles apply to all Media Types. The properties available to render will be different from Media Type to Media Type. For example, a File
will not have a Width property.
A media item is not only a reference to a static file. Like content, it is a collection of fields, such as width, height, and file path. This means that accessing and rendering media in a Template is similar to rendering content.
An uploaded image in the Media library is based on the Media Type Image
which has a number of standard properties:
Name
Width & Height
Size
Type (based on file extension)
UmbracoFile (the path to the file or JSON data containing crop information)
These standard properties are pre-populated and set during the upload process. For example, this means that the width and height are calculated for you.
If you want to add further properties to use with your Media Item, edit the Image Media Type under Settings. In this example, we are going to retrieve an image from the Media section. Then we will render out an img
tag using the URL of the media item and use the Name as the value for the alt
attribute.
The Media item in the following sample will use a sample Guid (55240594-b265-4fc2-b1c1-feffc5cf9571
). This example is not using Models Builder.
But wait a second, Umbraco comes with Models Builder. This means that you can use strongly typed models for your media items if Models Builder is enabled (which it is by default).
As with example one, we are accessing a MediaType image
using the same Guid assumption.
It is always worth having null-checks around your code when retrieving media in case the conversion fails or Media() returns null. This makes your code more robust.
File
Accessing other media items can be performed in the same way. The techniques are not limited to the Image
type, but it is one of the most common use cases.
The Image Cropper can be used with Image
Media Types and is the default option for the umbracoFile
property on an Image
Media Type.
When working with the Image Cropper for an image the GetCropUrl
extension method is used to retrieve cropped versions of the image. Details of the Image Cropper property editor and other examples of using it can be found in the Image Cropper article. The following is an example to help you get started with the Image Cropper.
This example assumes that you have set up a crop called square on your Image Cropper Data Type.
If you want the original, uncropped image, you can ignore the GetCropUrl extension method and use one of the previously discussed approaches as shown below.