Adding Umbraco Macro dynamically to user control
April 8, 2009
Today I had occasion to try and add an Umbraco macro to a User Control (.ascx) file.
Here’s how it’s done:
Umbraco Macro’s are just like normal UserControls so can be added to an user control using the standard Controls.Add() method.
However passing macro parameters proved to be a whole different ball game. This is because Macro parameters needed to be specified in lower case, despite the ones I was adding being in camel case in the Umbraco backend and the alias property not being case sensitive.
Here’s an example of the code I used to load my macro in with:
int ProductFolderID = 1188;
umbraco.presentation.templateControls.Macro mcr = new umbraco.presentation.templateControls.Macro();
As you can see creating and adding a macro is very simple, but watch out for the all lower case macro parameters and also that in the code that parameters are referred to as attributes.
For those who like a bit more detail here’s what the code above is doing:
First we create a new Macro object and assign it to the mcr variable for later use.
Note: the Macro object you need to create is in the following namespace: umbraco.presentation.templateControls.
Next up we update the alias property of the macro object. This tells umbraco which macro to use.
Note: this is not case sensitive.
Next we add the parameters to the macro, we do this by adding an entry into the MacroAttributes property, which is just a Hashtable. In my example the first parameter I add takes a value from a variable I have declared. The second parameter is a string literal I am passing direct to the hashtable.
The final line uses the standard Add() method on a PlaceHolder I have created in my usercontrol to add the umbraco macro to the page.