May 16, 2014

Using Orchard media profiles in your item body

Media profiles are a great feature in Orchard. Easily configurable image alteration without touching the original.

But right now the only way to use those profiles is in a custom template, as the example on the profile edit page suggests:

@Display.MediaUrl(Profile: "HeadlineThumbnail", 
                  Path: Model.ContentItem.Contact.Picture.Url)

Recently, I've found myself wishing I could use profiles directly in the Body part of my content items but couldn't find any official way to do that. So I came up with a simple solution by adding an alternate for the body part which I called Parts.Common.Body.html in my theme. Here's the content:

@using System.Text.RegularExpressions;
@{
  var regex = new Regex("src=\"(.*?)\\?profile=(.*?)\"", 
                        RegexOptions.Compiled);
  var html = regex.Replace(Model.Html.ToString(), 
                           new MatchEvaluator((match) => {
      return "src=\"" + 
              Display.MediaUrl(Profile: match.Groups[2].Value, 
                               Path: match.Groups[1].Value) + 
             "\"";
    }));
}

<div class="clearfix body-part">
  @Html.Raw(html)
</div>

Now when adding an image to the body, just append ?profile=<profile name> to the image URL and it will be replaced at render time by the correct URL.

This may not be the quickest option since it runs a regular expression on the entire body but that's what caching is for, right?

Comments powered by Disqus