How to Add Special Characters in i18N Translations

i18n is one of the most popular tools for website and application internationalization, and in some scenarios, it can be challenging to resolve specific issues when using i18n with your tool.

If you tried using characters like @ or { in i18n translation files in Vue.js and encountered a 500 error, this article will help you understand why this happened and teach you how to fix the problem.

The Problem with Certain Characters in I18N

Just like React.JS, which reserves certain HTML keywords such as class and for—replacing them with className and htmlFor—i18n also treats some characters in a special way:

  • {
  • }
  • @
  • $
  • |

If we don't handle these characters correctly, you may face the same error I encountered:

example of an error when adding special characters in i18n translation files

To understand the issue, let's consider a project with the following structure:

.
├── i18n <-- Folder containing i18n configurations
│   └── locales <--- Folder containing i18n translation files
│       ├── en.json <--- I18n translation file for English
│       └── pt-BR.json <--- I18n translation file for Brazilian Portuguese

Inside the pt-BR.json file, there are key-value pairs for the translated texts in Brazilian Portuguese. The problem started when I tried adding the @ character to one of the Footer links:

Special CharacterDescriptionSolution
@Used in URLs, emails, etc.{'@'}
{Start of a block in JSON{'{'}
}End of a block in JSON{'}'}
$Used in string interpolation{'$'}
|Pipe character{'|'}
{
  "footer": {
    "socialMedia": [
      {
        "url": "https://www.youtube.com/@CodigoAoPonto",
        "ariaLabel": "Go to Código ao Ponto's YouTube channel",
        "icon": "mdi:youtube"
      },
      {
        "url": "https://www.instagram.com/codigo_ponto",
        "ariaLabel": "Go to Código ao Ponto's Instagram",
        "icon": "mdi:instagram"
      }
    ]
  }
}

The Solution

To fix this issue, we need to use Literal Interpolation in i18n. To use the @ character in the i18n translation file, we should use the following syntax: {'@'}. This means wrapping the special character in curly braces and using single quotes.

Once applied, the corrected file will look like this:

{
  "footer": {
    "socialMedia": [
      {
        "url": "https://www.youtube.com/{'@'}CodigoAoPonto",
        "ariaLabel": "Go to Código ao Ponto's YouTube channel",
        "icon": "mdi:youtube"
      },
      {
        "url": "https://www.instagram.com/codigo_ponto",
        "ariaLabel": "Go to Código ao Ponto's Instagram",
        "icon": "mdi:instagram"
      }
    ]
  }
}

Conclusion

I hope this helps you overcome the challenge of using special characters in i18n with Vue.js. If you still have questions, you can check the Official VueI18n Documentation.