How to Use systemLanguage for Multilingual SVG

Creating multilingual SVG graphics and diagrams allows a single graphic asset to adapt seamlessly to users worldwide without requiring multiple files or complex JavaScript. By leveraging the native SVG systemLanguage attribute in combination with the <switch> element, SVG files can automatically detect a user’s browser or operating system language preferences and display the corresponding localized text, labels, and graphic components.

Understanding the systemLanguage Attribute

The systemLanguage attribute evaluates a comma-separated list of BCP 47 language tags (such as en, fr, es-MX, or ja). When an SVG renderer encounters this attribute, it compares the specified language tags against the user’s preferred language list configured in their browser or operating system. If a match is found, the attribute evaluates to true; otherwise, it evaluates to false.

How systemLanguage Works with the <switch> Element

While systemLanguage can be applied to individual elements, its primary utility comes from wrapping localized elements inside a <switch> container.

The <switch> element processes its direct child elements in sequential order from top to bottom. It renders the first direct child whose conditional processing attributes (like systemLanguage) evaluate to true, and completely ignores all subsequent sibling elements within that <switch> block.

Example Implementation

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 100" width="100%" height="100%">
  <switch>
    <!-- Displayed if user preference matches Spanish -->
    <text x="20" y="50" systemLanguage="es" font-size="20">
      Bienvenido a nuestro diagrama
    </text>
    
    <!-- Displayed if user preference matches French -->
    <text x="20" y="50" systemLanguage="fr" font-size="20">
      Bienvenue sur notre diagramme
    </text>
    
    <!-- Displayed if user preference matches German -->
    <text x="20" y="50" systemLanguage="de" font-size="20">
      Willkommen zu unserem Diagramm
    </text>
    
    <!-- Fallback: Default text when no language matches -->
    <text x="20" y="50" font-size="20">
      Welcome to our diagram
    </text>
  </switch>
</svg>

Key Advantages for Graphics and Diagrams

Best Practices for Implementation

  1. Always Include a Default Fallback: Place an element without a systemLanguage attribute at the very end of the <switch> block. If a user’s language does not match any specified options, the SVG displays this fallback rather than rendering a blank space.
  2. Order Specificity Correctly: Place regional dialects (e.g., pt-BR) above broader language codes (e.g., pt) inside the <switch> block to ensure regional users receive the intended specialized translation.
  3. Account for Text Expansion: German, French, and other languages often require more horizontal space than English. Ensure diagram bounding boxes and containers have enough padding to handle varying string lengths without clipping.