Render a block from ContentReference in EPiServer 7+

Just a quick post about something I didn’t find anywhere. If you for some reason have a ContentReference that is referencing a Block in EPiServer and you want to render the block using the default mechanism for resolving MVC templates in EPiServer, here is a HtmlHelper you can use
using EPiServer;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using EPiServer.Web;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MyProject.Mvc.Helpers
{
  public static class HtmlHelpers
  {
    public static IHtmlString RenderBlockByContentReference(this HtmlHelper htmlHelper, ContentReference blockContentReference)
    {
      if (blockContentReference == ContentReference.EmptyReference)
      {
          return null;
      }

      var contentRepository = ServiceLocator.Current.GetInstance();
      var block = contentRepository.Get(blockContentReference);
      
      if (block == null)
      {
          return null;
      }

      var templateResolver = ServiceLocator.Current.GetInstance();
      var template = templateResolver.ResolveMvcTemplate(HttpContext.Current.ContextBaseOrNull(), block);
      return htmlHelper.Partial(template.Name, block);
    }
  }
}

Usage:

@Html.RenderBlockByContentReference(Model.CurrentPage.MyContentReferenceProperty)