Jon Free
Jon Free

Reputation: 203

How do I pass an Umbraco property directly to a macro

I have an umbraco macro written in Razor. And I have a node with two media picker properties. I want the macro to simply take the media picker property, grab the image and then it's crops and then a specific crop and display it in an image tag. I have the macro working fine but I can't work out how pass a property name to the macro. Basically to prevent me from just copying the macro twice and editing depending on the property name I require.

My macro code is as follows. All I want to do is parametrize the @Model.imageId

    @{
var image = Model.MediaById(@Model.imageId);

if (image != null)
{    
    var crops = image.imageCropper.crops;

    if (crops != null || crops.GetType().ToString() != "System.String")
    {
        <img src="@crops.Find("@name", "home-promo").url" width="217" height="163" />
    } // if
}

}

Upvotes: 3

Views: 5026

Answers (1)

marapet
marapet

Reputation: 56446

If you define your Macro with a parameter imgId and call it like this:

<umbraco:Macro ID="Macro1" Alias="CropMacro" imgId="imageId" runat="server"></umbraco:Macro>

You're actually passing the name of the field "imageId". In the macro, you then may get the value of the Model's imageId property by using:

var image = Model.MediaById(Model.getProperty(Parameter.imgId).Value)

For an almost identical question & answer, as well as for how to do the same with helpers, see also here: Umbraco razor template - Get Formatted Date From Field specified in parameter

Upvotes: 2

Related Questions