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 has 5 years of experience with developing web solutions using ASP.NET and SQL Server. For the past 3 years, he has been actively engaged in website development projects using Sitecore CMS. He enjoys creating web solutions for clients using Sitecore CMS and, using its flexibility, provides cohesive and integrated solutions. Xing is a Sitecore Technology MVP, 2016.

Explore topics:

Other Blog Posts from Xing Liu

Subscribe for insights, trends and big ideas