1.2.2 • Published 12 months ago

@celseven/polyglot-nuxt v1.2.2

Weekly downloads
-
License
MIT
Repository
-
Last release
12 months ago

Polyglot Nuxt

A Nuxt 3 module for integrating with the Polyglot translation service.

Features

  • 🌐 Easy integration with Polyglot translation service
  • 🔄 Automatic caching of translations
  • 🔌 Simple API for translating content
  • 📝 Support for pluralization
  • 🔄 Support for variable replacement (Mustache-like syntax)

Installation

# npm
npm install polyglot-nuxt

# yarn
yarn add polyglot-nuxt

# pnpm
pnpm add polyglot-nuxt

Setup

Add the module to your nuxt.config.ts:

export default defineNuxtConfig({
  modules: ["@celseven/polyglot-nuxt"],
  polyglot: {
    organizationSlug: "your-organization",
    apiKey: "your-api-key",
    defaultLocale: "en",
    cache: {
      ttl: 300000, // 5 minutes
      maxSize: 100,
    },
  },
});

Usage

Basic Translation

<template>
  <div>
    <p>{{ $t("message.hello") }}</p>
  </div>
</template>

With Variable Replacement

<template>
  <div>
    <p>{{ $t("message.welcome", { replace: { name: "John" } }) }}</p>
    <!-- If message.welcome is "Welcome, {name}!", this will render "Welcome, John!" -->
  </div>
</template>

Pluralization

<template>
  <div>
    <p>{{ $t("item.count", { n: 0 }) }}</p>
    <!-- "No items" -->
    <p>{{ $t("item.count", { n: 1 }) }}</p>
    <!-- "1 item" -->
    <p>{{ $t("item.count", { n: 5 }) }}</p>
    <!-- "5 items" -->
  </div>
</template>

For this to work, your translation should be formatted like:

item.count: "No items | 1 item | {number} items"

Or for simpler cases:

item.count: "item | items"

Changing Locale

<template>
  <div>
    <button @click="changeLocale('en')">English</button>
    <button @click="changeLocale('fr')">French</button>
    <p>{{ $t("message.hello") }}</p>
  </div>
</template>

<script setup>
const { setLocale } = usePolyglot();

async function changeLocale(locale) {
  const success = await setLocale(locale);
  if (success) {
    console.log(`Locale changed to ${locale}`);
  } else {
    console.error(`Failed to change locale to ${locale}`);
  }
}
</script>

Loading Translation Spaces

By default, spaces are loaded automatically when you try to translate a key. However, you can also load spaces manually:

<script setup>
const { loadSpace } = usePolyglot();

// Load the 'common' space for the current locale
await loadSpace("common");

// Load the 'common' space for a specific locale
await loadSpace("common", "fr");
</script>

This is useful when you want to preload translations before they're needed.

Accessing the Polyglot Client

If you need direct access to the Polyglot client:

<script setup>
const { client } = usePolyglot();

// Now you can use client.getLanguages(), client.getSpaces(), etc.
</script>

License

MIT

1.2.2

12 months ago

1.2.1

12 months ago

1.2.0

12 months ago

1.1.0

12 months ago

1.0.6

12 months ago

1.0.5

12 months ago