Skip to content

Instantly share code, notes, and snippets.

@IvanLieckens
Created August 28, 2019 13:13
Show Gist options
  • Save IvanLieckens/0bf88c8d3becf93e468f95abc102e503 to your computer and use it in GitHub Desktop.
Save IvanLieckens/0bf88c8d3becf93e468f95abc102e503 to your computer and use it in GitHub Desktop.
Handy extension methods for RenderingParameters in Sitecore MVC
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Mvc.Presentation;
using Sitecore.Resources.Media;
namespace Foundation.Extensions
{
public static class RenderingParametersExtensions
{
public static string GetImageUrl(this RenderingParameters parameters, ID fieldId)
{
string result = string.Empty;
Item field = GetField(fieldId);
string numberBackgroundImageParameterValue = parameters?[field.Name];
if (!string.IsNullOrWhiteSpace(numberBackgroundImageParameterValue))
{
ImageField imageField = new ImageField(
new Field(fieldId, field),
numberBackgroundImageParameterValue);
if (imageField.MediaItem != null)
{
result = MediaManager.GetMediaUrl(imageField.MediaItem);
}
}
return result;
}
public static string GetValueOrDefault(this RenderingParameters parameters, ID fieldId, string defaultValue)
{
string result = defaultValue;
string fieldName = GetFieldName(fieldId);
if (!string.IsNullOrWhiteSpace(fieldName) && !string.IsNullOrWhiteSpace(parameters?[fieldName]))
{
result = parameters[fieldName];
}
return result;
}
private static Item GetField(ID fieldId)
{
Item result = Sitecore.Context.Database.GetItem(fieldId);
if (result == null)
{
Log.Error($"Could not find the field '{fieldId}'.", typeof(RenderingParametersExtensions));
}
return result;
}
private static string GetFieldName(ID fieldId)
{
string result = null;
Item field = GetField(fieldId);
if (field != null)
{
result = field.Name;
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment