2

If image field is null or empty @RenderImage does not render the <img> attribute.

Is there a way to tell GlassMapper's @RenderImage to use default placeholder image if no image exists or comes from sitecore?

Can we set this configuration sitewide?

3 Answers 3

3

An alternative would be a custom Data Mapper that replaces the standard SitecoreFieldImageMapper. You could then set a default image for every empty field.

However I think that a custom extension to GlassHtml, e.g RenderImageWithPlaceholder, would be a better solution.

4

It is not possible "out-of-the-box" as far as I am aware. And instead of creating a new version of the @RenderImage method to allow this, I would do this check in your model before you hand it over to your view. If you are using a controller rendering, I would do something like:

if (model.MyImage == null)
{
    model.MyImage = new Image()
    {
        Src = "/mydefaultImage.jpg", 
        Alt = string.Empty
    };
}

You could probably wrap your SitecoreContext.GetItem<T> and apply this to all Glass.Mapper.Sc.Fields.Image's in your model if you want to use the same default image in all of your models.

0

This is how i solved this, for future reference:

Created an extension method for Glass.Mapper.Sc.Fields.Image which returns default image placeholder if image field is Null or empty.

    public static Image GetDefaultPlacholderImage(this Image image)
    {
        if (string.IsNullOrEmpty(image?.Src))
        {
            return new Image { Src = Core.Constants.Constants.PlaceholderImagePath, Alt = string.Empty };
        }
        return image;
    }

In cshtml:

@RenderImage(child, x => x.ListingDetailsImage.GetDefaultPlacholderImage())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.