Sitecore Render Image with Glass Mapper

Posted by Xing Liu on 7/3/2015

In Sitecore, since it handles the media items through media url, there are query string parameters to control the media item’s properties.  Below are some of them for images:

  • w: Width in pixels
  • h: Height in pixels
  • mw: Maximum width in pixels
  • mh: Maximum height in pixels

For a complete list, you can check out John West post on the query string parameters: http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2011/05/media-options-and-query-string-parameters-in-the-sitecore-aspnet-cms.aspx

In a regular page scenario, w and h parameters will add a fixed width to the image tag.  However, this won’t work under the responsive design framework.  In responsive design, if the image has fixed width and the screen is resized, the image will go out of bound.  In this case, the image will resize according to the screen size and will not exceed the maximum size on the image.  For Glass Mapper, since using RenderImage function, it’s using different way to append the query string parameter.

The regular way to render an image in Glass Mapper is like the following:

@RenderImage(Model, x => x.FeaturedImage, isEditable: true)

If you want to have the parameters to control the maximum width for the image, it will be written as a property object parameter, shown below:

@RenderImage(item, x => x.FeaturedImage, new { mw = 600 }, isEditable: true)

This will produce the equivalent image html tag like the following:

<img src="/~/media/Site/image.ashx?mw=600" alt="image" />

In this way, the maximum width of the image will not exceed 600 pixels and will adjust the width whenever the screen is resized to a smaller size.  



CONTACT SYMSOFT SOLUTIONS

Looking for a partner who will exceed your expectations? Get in touch.

Name
*
Message
*
SYMSOFT SOLUTIONS 4090 Truxel Road, Suite 200 Sacramento, CA 95834
United States (916) 567-1740