Get Content with Language Fallback

Howdy!

Today is basically just a short gist I had to add as a workaround recently.

So, when working with content in multiple languages in Episerver we have the option of configuring fallback languages. This is made by selecting Language options for a content page. This could be done on Root level or further down in the hierarchy. Typically, a “lesser” language should present a default language fallback version of content if a translated version doesn’t exist.

Normally we just get content in the APIs using IContentLoader or IContentRepository and the Get method with a ContentReference and optionally CultureInfo as well. While this gives us the specific language version (if it exists), there are cases where we would like to also retrieve the fallback version if such a version is defined. A small code example below.

public IContent GetContentWithFallback(ContentReference contentLink, CultureInfo preferredLanguage)
{
  // This should be ctor injected
  var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();

  // Define the fallback behavior, additional fallback to master language version is also an option
  var loaderOptions = new LoaderOptions().Add(LanguageLoaderOption.Fallback(preferredLanguage));
  var contentExists = contentLoader.TryGet(contentLink, loaderOptions, out IContent content);
  
  return contentExists ? content : null;
}

Cheers!