A critical vulnerability was discovered in React Server Components (Next.js). Our systems remain protected but we advise to update packages to newest version. Learn More

Deepmala S
Sep 3, 2025
  5
(0 votes)

Custom Deepl Glossary Translation in Optimizely CMS

Introduction in this post, I have created a custom DeepL glossary translation for specific words. For example, when translating from English to German, the standard translation for "Hello" is "Hallo." However, using my custom DeepL glossary, I want "Hello" to be translated as a custom word like "Ollha." This custom translation will override the normal Optimizely auto-translation and ensure that the glossary-defined terms are used instead.

Repository link for reference

https://github.com/mattpallatt/MP.LanguageManager.DeepLTranslate

 

1)      Install nuget package MP.LanguageManager.DeepLTranslate

 dotnet add package MP.LanguageManager.DeepLTranslate --version 1.0.9

2) Create DeepLTranslateProvider class

 
public class DeepLTranslateProvider : IMachineTranslatorProvider
    {
        private readonly Injected<IOptions<DeepLOptions>> _options;

        public string DisplayName => "DeepL Web Translator";

        public DeepL.Formality DLFormality = DeepL.Formality.Default;
        public string EnglishType = "";
        public string authkey = "";
        public string AutoGlossary = "";
        public string GlossaryList = "";

        public bool Initialize(ITranslatorProviderConfig config)
        {
            var languageManagerOptions = new LanguageManagerOptions();
            var languageManagerConfig = new LanguageManagerConfig(languageManagerOptions);
            authkey = languageManagerConfig.ActiveTranslatorProvider.SubscriptionKey;
            var options = _options.Service.Value;
            var dlfv = "default";

            try
            {
                dlfv = (options.Formality.ToLower() == "default" || options.Formality.ToLower() == "more" || options.Formality.ToLower() == "less" || options.Formality.ToLower() == "preferless" || options.Formality.ToLower() == "prefermore") ? options.Formality.ToLower() : dlfv;
                EnglishType = (options.English.ToLower() == "en-gb" || options.English.ToLower() == "en-us") ? options.English.ToLower() : "en-gb";
                AutoGlossary = (options.AutoGlossary == "0" || options.AutoGlossary == "1") ? options.AutoGlossary : AutoGlossary;
                GlossaryList = options.GlossaryList;
            }
            catch { }

            // free API authorisation keys end in :fx...
            if (authkey.EndsWith(":fx"))
            {
                // ...set the formality to Default, as this is a Pro feature
                DLFormality = DeepL.Formality.Default;
            }
            else
            {
                DLFormality = dlfv.ToLower() switch
                {
                    "less" => DeepL.Formality.Less,
                    "more" => DeepL.Formality.More,
                    "preferless" => DeepL.Formality.PreferLess,
                    "prefermore" => DeepL.Formality.PreferMore,
                    _ => DeepL.Formality.Default,
                };
            }
            return true;
        }

        public TranslateTextResult Translate(string inputText, string sourceLanguage, string targetLanguage)
        {
            var translateTextResult = new TranslateTextResult
            {
                IsSuccess = true,
                Text = ""
            };

            if (string.IsNullOrWhiteSpace(inputText))
            {
                return translateTextResult;
            }

            try
            {
                var n = DoTranslate(inputText, sourceLanguage, targetLanguage);
                n.Wait();

                translateTextResult.Text = n.Result.ToString();
                translateTextResult.IsSuccess = true;
            }
            catch (Exception ex)
            {
                translateTextResult.IsSuccess = false;
                translateTextResult.Text = "An unexpected error occurred: " + ex.Message + ex.InnerException;
            }

            return translateTextResult;
        }
        public async Task<TextResult> DoTranslate(string inputText, string sourceLanguage, string targetLanguage)
        {

            var slci = new CultureInfo(sourceLanguage);
            var tlci = new CultureInfo(targetLanguage);
            string tl = tlci.TwoLetterISOLanguageName.ToString();

            // deal with PT, ZH (xx-xx) language codes
            if (tl == "pt" || tl == "zh")
            {
                tl = targetLanguage;
            }
            // dealing with depreciated "en" target language code using default EN code
            else if (tl == "en")
            {
                tl = EnglishType;
            }
            // reset the glossary ID
            string glossaryID = "";

            var translator = new DeepL.Translator(authkey);

            if ((AutoGlossary == "1") || (GlossaryList.Contains($"[{slci}>{tlci}]")))
            {
                System.Threading.Tasks.Task<GlossaryInfo[]> n = translator.ListGlossariesAsync();
                n.Wait();
                List<GlossaryInfo> GI = n.Result.ToList();
                glossaryID = GI.FirstOrDefault(item => item.SourceLanguageCode == slci.ToString() && item.TargetLanguageCode == tlci.ToString())?.GlossaryId;
            }

            var translatedText = await translator.TranslateTextAsync(
                inputText,
                slci.TwoLetterISOLanguageName.ToUpper(),
                tl.ToUpper(),
                new TextTranslateOptions { Formality = DLFormality, TagHandling = "html", GlossaryId = glossaryID }
                );

            return translatedText;
        }
    }
     public class DeepLOptions
    {
        public string Formality { get; set; }
        public string English { get; set; }
        public string AutoGlossary { get; set; }
        public string GlossaryList { get; set; }
        public string ignoreExistingPages { get; set; }
    }

3) Create API Controller

 [HttpPost]
 [Route("/api/v1/glossary/create")]
 public async Task<ActionResult> Create([FromBody] GlossaryDTO glossaryDTO)
 {
     var timer = Stopwatch.StartNew();
     GlossaryInfo glossaryInfo = null;

     try
     {
          if (glossaryDTO != null)

         {
             glossaryInfo = await _glossary.CreateGlossaryAsync(glossaryDTO.Name, glossaryDTO.SourceLang, glossaryDTO.TargetLang, glossaryDTO.GlossaryEntries);
         }

     }
     catch (Exception ex)
     {
         _logger.LogError(nameof(Index), ex, "Error GlossaryController getting GlossaryController");
         return StatusCode(500, new { message = ex.Message });
     }

     timer.Stop();

     _logger.LogInformation(nameof(Index), $"Timer took {timer.ElapsedMilliseconds}ms");

     return new JsonResult(new { message = glossaryInfo != null ? "Glossary has been created" : "Glossary is not created", glossary = glossaryInfo });

 }

4)  Do App setting configurations

5)   Set up Deepl Web Translator in Language manager plug in.

        To use the DeepL Translator to perform automated translations make sure it's selected as Translator Provider in the settings of the Language Manager

6)   Create Glossary block and on view create glossaries. Set access right on block hide from visitors. 

6)    Do auto translation from Language gadget.




 

 

Sep 03, 2025

Comments

Please login to comment.
Latest blogs
A day in the life of an Optimizely OMVP: Learning Optimizely Just Got Easier: Introducing the Optimizely Learning Centre

On the back of my last post about the Opti Graph Learning Centre, I am now happy to announce a revamped interactive learning platform that makes...

Graham Carr | Jan 31, 2026

Scheduled job for deleting content types and all related content

In my previous blog post which was about getting an overview of your sites content https://world.optimizely.com/blogs/Per-Nergard/Dates/2026/1/sche...

Per Nergård (MVP) | Jan 30, 2026

Working With Applications in Optimizely CMS 13

💡 Note:  The following content has been written based on Optimizely CMS 13 Preview 2 and may not accurately reflect the final release version. As...

Mark Stott | Jan 30, 2026

Experimentation at Speed Using Optimizely Opal and Web Experimentation

If you are working in experimentation, you will know that speed matters. The quicker you can go from idea to implementation, the faster you can...

Minesh Shah (Netcel) | Jan 30, 2026