In Umbraco, we can customise the user experience in several different ways.  One handy feature to allow content editors to add re-usable components onto a page is to implement custom macros in your project.  In case you haven't run into macro's before, a macro is a reusable piece of code that developers can build into an Umbraco project, that allows content editors to add into any rich text block that's defined on any document type within the site.

When we define a macro, we can define one or more parameters to be associated with it.  When a content editor drops the macro into a text area, they can populate these parameters which can be used to render the macro.  There are two types of macros in Umbraco, partial view macros (via code) and XSLT macros.  It is best practice to only use partial via macros and this is the option we will explore in today's tutorial.

Creating a Macro

To create a macro, in your '~/Views/MacroPartials' folder, create a new .cshtml file/view. The view will need to inherit from 'Umbraco.Web.Macros.PartialViewMacroPage'. The PartialViewMacroModel base type contains everything required to render the macro, including things like MacroName, MacroAlias, MacroId, and MacroParameters.


To access a macro parameter, you can use the MacroParameters property.  Under the hood, MacroParameters is a simple dictionary, so you can add any key/value combo you want into it.

Creating A Macro In Umbraco

Now we've covered some of the basics about macro and how to create the code for it, I'll cover how to create this basic macro within Umbraco. First, log into the Umbraco backend, click on the developer section, click 'Macros' and click create:


In the Macro Properties, select 'MVC Partial view' and from here select your macro view in MVC; for a very basic example of what a view would look like, see this:

From this screen, we can add any parameters that we want to pass to our views. In the 'Properties' tab you can create as many parameters as you need. For each parameter, you can add a name, an alias and it's type. The type can be Content Type Picker, Multiple Content Type Picker, Multiple Media Picker, Multiple Tab Picker, Multiple Property Type Picker, Tab Picker, Property Type Picker, Single Media Picker, Numeric, Content Picker, Textarea or Textbox.

Adding A Macro

To add a macro to a page, go to the Content section and find a document type that has a text area property and select the 'Macro' button.


Select, the macro name and add in any parameters you have defined:


When you render the page the macro will be displayed. It's as simple as that.


In today's post, we've covered what an Umbraco macro is and how to implement it within your project. To do this, you create a partial view as usual and use PartialViewMacroPage as the model. In Umbraco, create a new macro, use the view as the default view to render. After you add the macro into a text area it will then display on the page.