Building Multilingual Applications with i18n

CK CK 3788 
Created at  
1,209 0 0

What is i18n?

i18n stands for internationalization. It's a process of designing and developing applications, websites, and other software in a way that they can be adapted to various languages, regions, and cultural conventions *without requiring engineering changes*.

Think of it as preparing your software for localization. i18n focuses on the technical architecture that *enables* localization. It involves:

  • Abstracting text and other locale-specific data: This means separating text, dates, numbers, currencies, etc., from the core code.
  • Using character encoding that supports multiple languages: UTF-8 is the most common.
  • Designing flexible layouts that can accommodate different text lengths:Some languages are more verbose than others.
  • Handling date, time, and number formats correctly for different locales:This includes things like decimal separators, date order, and currency symbols.
  • Supporting right-to-left languages, like Arabic or Hebrew.
  • Considering cultural sensitivities: Colors, symbols, and images may have different meanings in different cultures.

Building Multilingual Applications with i18n

In essence, i18n sets the stage for making your software usable in a global context.

 

 

Structuring Multi-Language Contextual Metadata for Delivery

When delivering contextual metadata in multiple languages, you need a robust structure that allows you to easily manage and deliver the correct language version based on the user's locale. Here's how you can approach it:

1. Key-Value Pair Storage with Locale Identifiers:

  • Principle: The fundamental approach is to store each piece of contextual metadata (e.g., a description, a title, a label) as a key-value pair. The key is a unique identifier, and the value is a dictionary (or similar structure) containing the translations for different locales.
  • Example (JSON):
  • Explanation:
    • "product_description" and "product_title" are keys representing the data.
    • Each key's value is an object (dictionary).
    • Within that object, the keys are locale identifiers (e.g., "en-US" for English (United States), "fr-FR" for French (France)).
    • The values associated with the locale identifiers are the translated strings.

 

2. Locale Identifiers (Language Tags):

  • Importance: Using standard language tags (following the BCP 47 specification) is *crucial*. This ensures consistent and accurate language identification.
  • Structure: A language tag typically consists of:
    • language: (Required) A two- or three-letter ISO 639 language code (e.g., en, fr, de, es).
    • script: (Optional) An ISO 15924 script code (e.g., Latn for Latin, Cyrl for Cyrillic).
    • region: (Optional) An ISO 3166-1 alpha-2 country code (e.g., US, FR, DE, ES).
    • variants: (Optional) Further specifies dialectal variations.
  • Examples:
    • en-US: English (United States)
    • fr-CA: French (Canada)
    • zh-Hans: Chinese (Simplified)
    • zh-Hant: Chinese (Traditional)

 

3. Data Storage Options:

  • JSON Files: Suitable for smaller datasets and simple configurations. The example above is JSON. Easy to read and edit manually.
  • Property Files: Similar to JSON but uses a different syntax (key=value). Common in Java-based applications.
  • Databases: Ideal for larger, more complex datasets. You can create tables with columns for the key, locale, and translated value.
  • Content Management Systems (CMS): Many CMS platforms have built-in i18n and localization features that simplify the process of managing and delivering multilingual content.
  • Translation Management Systems (TMS): Specialized tools for managing the translation workflow, storing translations, and ensuring consistency.
  • Resource Bundles: In languages like Java, resource bundles provide a way to group locale-specific resources (text, images, etc.) into separate files.

 

 

How do we build the i18n structure?

File Structure

/i18n/
  en.json
  es.json
  ko.json
index.html
app.js

 

Example of JSON dictionaries:

en.json

{
  "app.title": "Hello, world!",
  "greeting.named": "Hi, {name}!",
  "inbox.count": "{count} message |||| {count} messages",
  "date.today": "Today is {date}",
  "errors.missing": "Missing translation: {key}"
}

ko.json

{
  "app.title": "안녕하세요!",
  "greeting.named": "{name}님, 안녕하세요!",
  "inbox.count": "{count}개 메시지",
  "date.today": "오늘은 {date}",
  "errors.missing": "번역이 없습니다: {key}"
}

 

Minimal HTML: index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>i18n JSON Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <label>
      Language:
      <select id="lang">
        <option value="en" selected>English</option>
        <option value="es">Español</option>
        <option value="ko">한국어</option>
      </select>
    </label>

    <h1 data-i18n="app.title"></h1>

    <p data-i18n="greeting.named" data-params='{"name":"Chun"}'></p>

    <p>
      <span data-i18n="inbox.count" data-params='{"count":1}'></span><br />
      <span data-i18n="inbox.count" data-params='{"count":5}'></span>
    </p>

    <p data-i18n="date.today"></p>

    <script src="app.js"></script>
  </body>
</html>

 

Loader + translator: app.js

const I18N = (() => {
  const cache = new Map();
  let current = "en";
  let fallback = "en";

  async function load(lang) {
    if (!cache.has(lang)) {
      const res = await fetch(`/i18n/${lang}.json`);
      if (!res.ok) throw new Error(`Failed to load ${lang}`);
      cache.set(lang, await res.json());
    }
    return cache.get(lang);
  }

  function interpolate(str, params = {}) {
    return str.replace(/\{(\w+)\}/g, (_, k) => (params[k] ?? `{${k}}`));
  }

  // Very simple pluralization: split forms with "||||"
  function pluralize(template, count) {
    if (!template.includes("||||")) return template;
    const [one, many] = template.split("||||").map(s => s.trim());
    return count === 1 ? one : many;
  }

  function lookup(dict, key) {
    return key.split(".").reduce((o, k) => (o ? o[k] : undefined), dict);
  }

  async function t(key, params = {}) {
    const dict = await load(current);
    let val = lookup(dict, key);

    if (val == null) {
      // try fallback
      if (current !== fallback) {
        const fb = await load(fallback);
        val = lookup(fb, key);
      }
    }

    if (val == null) {
      const fb = await load(fallback);
      val = lookup(fb, "errors.missing") || "Missing translation: {key}";
      return interpolate(val, { ...params, key });
    }

    // handle pluralization if count provided
    if (typeof params.count === "number") {
      val = pluralize(val, params.count);
    }
    return interpolate(val, params);
  }

  async function setLanguage(lang) {
    current = lang;
    await load(lang);
    await renderAll();
  }

  async function renderAll() {
    const nodes = document.querySelectorAll("[data-i18n]");
    for (const el of nodes) {
      const key = el.getAttribute("data-i18n");
      const params = JSON.parse(el.getAttribute("data-params") || "{}");

      // example: dynamic date param
      if (key === "date.today") {
        params.date = new Date().toLocaleDateString(current);
      }

      el.textContent = await t(key, params);
    }
  }

  return { t, setLanguage, renderAll, setFallback: f => (fallback = f) };
})();

window.addEventListener("DOMContentLoaded", async () => {
  I18N.setFallback?.("en");
  await I18N.setLanguage("en");

  document.getElementById("lang").addEventListener("change", async e => {
    await I18N.setLanguage(e.target.value);
  });
});

 

Notes & tips

  • Pluralization: This demo uses a very simple "one||||many" split. For production, consider proper CLDR rules (e.g., via Intl.PluralRules).
  • Interpolation: {name} and {count} are replaced from data-params. You can pass any variables you need.
  • Fallbacks: If a key is missing in the active language, it tries the fallback (en) and shows a missing string if still not found.
  • Server paths: Adjust /i18n/${lang}.json if your files are served from a different path.

 

 

If you want to consolidate all the translation in a single JSON.

Below example will help you to have better understanding:

{
  "en": {
    "app": {
      "title": "Hello, world!"
    },
    "greeting": {
      "named": "Hi, {name}!"
    },
    "inbox": {
      "count": "{count} message |||| {count} messages"
    },
    "date": {
      "today": "Today is {date}"
    },
    "errors": {
      "missing": "Missing translation: {key}"
    }
  },

  "es": {
    "app": {
      "title": "¡Hola, mundo!"
    },
    "greeting": {
      "named": "¡Hola, {name}!"
    },
    "inbox": {
      "count": "{count} mensaje |||| {count} mensajes"
    },
    "date": {
      "today": "Hoy es {date}"
    },
    "errors": {
      "missing": "Falta traducción: {key}"
    }
  },

  "ko": {
    "app": {
      "title": "안녕하세요!"
    },
    "greeting": {
      "named": "{name}님, 안녕하세요!"
    },
    "inbox": {
      "count": "{count}개 메시지"
    },
    "date": {
      "today": "오늘은 {date}"
    },
    "errors": {
      "missing": "번역이 없습니다: {key}"
    }
  }
}

 

When you use an element, you can use it like below:

lang = "ko"
print( translation[ lang ][ "app" ][ "title" ] )

 

You can also flip the structure for better management, like below:

{
  "app.title": {
    "en": "Hello, world!",
    "es": "¡Hola, mundo!",
    "ko": "안녕하세요!"
  },
  "greeting.named": {
    "en": "Hi, {name}!",
    "es": "¡Hola, {name}!",
    "ko": "{name}님, 안녕하세요!"
  },
  "inbox.count": {
    "en": "{count} message |||| {count} messages",
    "es": "{count} mensaje |||| {count} mensajes",
    "ko": "{count}개 메시지"
  },
  "date.today": {
    "en": "Today is {date}",
    "es": "Hoy es {date}",
    "ko": "오늘은 {date}"
  },
  "errors.missing": {
    "en": "Missing translation: {key}",
    "es": "Falta traducción: {key}",
    "ko": "번역이 없습니다: {key}"
  }
}

Then you will be able to use the element like below:

lang = "ko"
print( translation[ "app.title" ][ lang ]

 

Tags Contextual Metadata Internationalization Multi Language i18n Facebook X
Comments 0
  1. Redis vs Memcached: Why Enterprise Tech Giants Choose Redis
    261
  2. ETL vs ELT what makes the differeence? Why MLOps leverage ELT?
    202
  3. Arm Kernel DNNs: Powering Efficient AI at the Edge
    230
  4. Cloud-Native Capital Markets: Architecture, Compliance, and Innovation
    218
  5. Add New Address to gmail without SMTP (forwarding-only-address)
    1,701
  6. Registering an App on the Google Play Store
    1,481
  7. AGENT.md: AI's Blueprint for Robust Software and Vibe Coding
    563
  8. Tailscale: Zero-Config Remote Access to Your Home PC, Firewall-Free
    539
  9. Markdown's Visual Revolution: Meet Mermaid.js
    417
  10. Viewing Git Graph in ASCII
    600
  11. Vibe Coding: Harmonizing Intent with AI Productivity
    505
  12. How do I change the theme for code block in Confluence Cloud?
    1,397
  13. FIPS - Federal Information Processing Standards
    1,406
  14. Simplify Your Workflow: Switching Git Profiles Automatically by Folder
    760
  15. How to Control External Monitor Brightness, Sound Volume on a Mac with MonitorControl (Even Over HDMI)
    2,410
  16. Kiro versus Cursor AI - Spec-Driven? or Chat-Driven?
    408
  17. How to use multiple RSA (SSH) keys for GitHub
    337
  18. Key Metrics Track to Ensure the Health and Performance of a Distributed System
    181
  19. REST API Vs. GraphQL
    414
  20. Project Libre similar to MS Project
    533
  21. Learning about Firestore: Architecture, Pros, Cons, and Real-World Deployments
    173
  22. Building Privacy-First Infrastructure: Network Isolation + Zero Trust for GDPR Compliance
    298
  23. Why supabase is not safe for the Fintech project?
    862
  24. The Ultimate Data Engineering Roadmap
    1,084
  25. Nine Types of Testing while we develop APIs
    519
  26. Apache Kafka - a distributed, fault-tolerant, high-throughput streaming platform
    618
  27. Comprehensive Software Development Flow : How Companies Ship Code To Production
    2,334
  28. DeepSeek v3 offers of ChatGPT's performance at 1/10 the price!
    639
  29. Difference between CPU and GPU - Why GPU is faster than CPU?
    809
  30. gRPC - Open-source Universal RPC Framework developed by Google
    770
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,254
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233