Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sitecore - Image field in parameter template

Tags:

sitecore

If I have an image field in a parameter template, what are the steps involved in getting the URL of the image in c#?

like image 729
Martin Davies Avatar asked Nov 06 '13 22:11

Martin Davies


2 Answers

@mdresser makes a valid point about what should and should not be a rendering parameter. However, I don't think that Sitecore intentionally made it difficult to use image fields in parameter templates. They simply built the parameter template functionality over the existing key-value pair rendering parameter functionality.

If the name of your image field on the rendering parameters template was BackgroundImage, you could use the following code to get the URL of the selected image:

var imageId = XmlUtil.GetAttribute("mediaid", XmlUtil.LoadXml(this.Parameters["BackgroundImage"]));
MediaItem imageItem = Sitecore.Context.Database.GetItem(imageId);
backgroundImageUrl = MediaManager.GetMediaUrl(imageItem);

If you don't already have a base class for your sublayouts that provides the Parameters property, you will need to also add this:

private NameValueCollection parameters;
public virtual NameValueCollection Parameters
{
    get
    {
        if (this.parameters == null)
        {
            var parameters = this.Attributes["sc_parameters"];
            this.parameters = string.IsNullOrEmpty(parameters)
                                  ? new NameValueCollection()
                                  : WebUtil.ParseUrlParameters(parameters);
        }
        return this.parameters;
    }
}
like image 197
Ben Golden Avatar answered Sep 22 '22 21:09

Ben Golden


To achieve this you would have to look at how the sitecore image field renders the raw text value into an img tag. However, there is a reason that this doesn't work out of the box with sitecore; parameters templates are designed to define info about how a rendering or sublayout should render. E.g. You could use it to tell a list control to show a certain number of items etc. I'd advise against using rendering parameters for content as this will make content editing very cumbersome. If your aim is to have the content of a particular sublayout defined somewhere other than the page itself, put it into a sub item instead.

like image 28
Matthew Dresser Avatar answered Sep 20 '22 21:09

Matthew Dresser