Sitecore Render Image with Glass Mapper

Xing Liu • 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:

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.  

Xing Liu

Xing Liu is a Sitecore MVP with expertise in all aspects of ASP.NET and SQL Server development across a variety of industries including Government, Banking, Healthcare and Energy. He provides technical thought leadership and consulting to SymSoft and client development teams. Xing has deep expertise in using Sitecore Helix in an Agile delivery model to streamline the construction of complex Sitecore websites, portals and their associated authoring environments. Xing is also a globally recognized photographer with an Instagram following approaching 100,000.

Explore topics:

Other Blog Posts from Xing Liu