6

Using Fortis Image.Render, is there a parameter to suppress rendering the Width and Height attributes?

Example of the image:

@Model.ImageField.Render(new { @class = "my-class-name" })
6

You can't do that out of the box with Fortis because under the hood it is just using the standard Sitecore Field Renderer. This is what is adding the width and height attributes.

There is a nice solution here that adds a new processor to the RenderField pipeline that strips out those attributes if a parameter called responsive is added. With Fortis you would call it like this in your razor view:

@Model.ImageField.Render(new { responsive = true })

The code for the processor is as follows. It uses a simple regex to remove the width and height attributes from the rendered markup if the responsive parameter exists. It then removes the responsive tag that gets added by the field renderer too.

namespace SitecoreCustomization.Pipelines.RenderField
{
    public class GetImageFieldValueResponsive
    {
        public void Process(RenderFieldArgs args)
        {
            if (args.FieldTypeKey != "image")
                return;
            if (args.Parameters.ContainsKey("responsive"))
            {
                string imageTag = args.Result.FirstPart;
                imageTag = Regex.Replace(imageTag, @"(<img[^>]*?)\s+height\s*=\s*\S+", "$1", RegexOptions.IgnoreCase);
                imageTag = Regex.Replace(imageTag, @"(<img[^>]*?)\s+width\s*=\s*\S+", "$1", RegexOptions.IgnoreCase);
                imageTag = Regex.Replace(imageTag, @"(<img[^>]*?)\s+responsive\s*=\s*\S+", "$1", RegexOptions.IgnoreCase);
                args.Result.FirstPart = imageTag;
            }

        }
    }
}

Then you can patch it in like this:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <renderField>
        <processor 
            patch:after="*[@type='Sitecore.Pipelines.RenderField.GetImageFieldValue, Sitecore.Kernel']" 
            type="SitecoreCustomization.Pipelines.RenderField.GetImageFieldValueResponsive, SitecoreCustomization"/>
      </renderField>
    </pipelines>
  </sitecore>
</configuration>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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