### Set initial and fallback locales
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Migration.md
Compares v1 manual locale setting with the unified init() configuration pattern introduced in v2.
```javascript
// v1
import { getClientLocale, locale } from 'svelte-i18n'
locale.set(getClientLocale({ fallback: 'en', navigator: true }))
```
```javascript
// v2
import { init } from 'svelte-i18n'
init({
fallbackLocale: 'en',
initialLocale: { navigator: true },
})
```
--------------------------------
### Add custom formats
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Migration.md
Demonstrates moving custom format definitions from a standalone function in v1 to the init configuration object in v2.
```javascript
// v1
import { addCustomFormats } from 'svelte-i18n'
addCustomFormats({ number: { EUR: { style: 'currency', currency: 'EUR' } } })
```
```javascript
// v2
init({
formats: {
number: { EUR: { style: 'currency', currency: 'EUR' } },
}
})
```
--------------------------------
### Setup svelte-i18n with Locales
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Svelte-Kit.md
Initializes svelte-i18n by registering locales and setting the initial locale based on browser environment or a default. Requires the 'svelte-i18n' library.
```typescript
import {
browser
} from '$app/environment'
import {
init,
register
} from 'svelte-i18n'
const defaultLocale = 'en'
register('en', () => import('./locales/en.json'))
register('de', () => import('./locales/de.json'))
init({
fallbackLocale: defaultLocale,
initialLocale: browser ? window.navigator.language : defaultLocale,
})
```
--------------------------------
### Localize UI Components
Source: https://github.com/kaisermann/svelte-i18n/wiki/Home
Use the translation store (aliased as _) to format and display translated strings within Svelte components.
```svelte
{$_.upper('page_title')}
```
--------------------------------
### Install svelte-i18n and @rollup/plugin-json
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Getting Started.md
Installs the svelte-i18n library and the @rollup/plugin-json for handling JSON imports, which is necessary when using Rollup.
```shell
yarn add svelte-i18n
# if using rollup so we can import json files
yarn add -D @rollup/plugin-json
```
--------------------------------
### Initialize svelte-i18n
Source: https://github.com/kaisermann/svelte-i18n/wiki/Home
Configure the library using the init function to define fallback and initial locales. This bootstrap process ensures the application is ready to handle locale changes.
```javascript
import { register, init } from 'svelte-i18n'
register('en', () => import('./en.json'))
register('en-US', () => import('./en-US.json'))
register('pt', () => import('./pt.json'))
init({
fallbackLocale: 'en',
initialLocale: {
navigator: true
}
})
```
--------------------------------
### Implement casing utilities in Svelte-i18n
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Migration.md
Shows how to replace removed v2 casing utilities with native JavaScript string methods and custom helper functions in v3.
```javascript
// v2
$_.lower('message.id')
$_.upper('message.id')
$_.title('message.id')
$_.capital('message.id')
```
```javascript
// v3
function capital(str: string) {
return str.replace(/(^|\s)\S/, l => l.toLocaleUpperCase())
}
function title(str: string) {
return str.replace(/(^|\s)\S/g, l => l.toLocaleUpperCase())
}
$_('message.id').toLocaleLowerCase()
$_('message.id').toLocaleUpperCase()
title($_('message.id'))
capital($_('message.id'))
```
--------------------------------
### Manage dictionaries in Svelte-i18n
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Migration.md
Illustrates the migration from direct store manipulation in v1 to the addMessages API in v2 for dictionary management.
```javascript
// v1
import { dictionary } from 'svelte-i18n'
dictionary.set({
en: { ... },
pt: { ... },
})
```
```javascript
// v2
import { addMessages } from 'svelte-i18n'
addMessages('en', { ... })
addMessages('pt', { ... })
```
--------------------------------
### Format numbers, dates, and times in Svelte-i18n
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Migration.md
Demonstrates the transition from v2 formatter methods to v3 tree-shakeable stores for improved performance and modularity.
```javascript
// v2
$_.time(dateValue)
$_.date(dateValue)
$_.number(100000000)
```
```javascript
// v3
import { time, date, number } from 'svelte-i18n'
$time(someDateValue)
$date(someDateValue)
$number(100000000)
```
--------------------------------
### Configure client locale detection
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Migration.md
Explains the shift from automatic locale detection in v2 to explicit utility imports in v3 to reduce bundle size.
```javascript
// v2
import { init } from 'svelte-i18n'
init({
initialLocale: {
navigator: true,
},
})
```
```javascript
// v3
import { init, getLocaleFromNavigator } from 'svelte-i18n'
init({
initialLocale: getLocaleFromNavigator(),
})
```
--------------------------------
### Example Translation JSON (English)
Source: https://github.com/kaisermann/svelte-i18n/blob/main/README.md
This JSON file represents a sample dictionary for the English locale ('en.json'). It contains nested key-value pairs for different sections of a web page, such as titles and navigation links.
```jsonc
// en.json
{
"page": {
"home": {
"title": "Homepage",
"nav": "Home"
},
"about": {
"title": "About",
"nav": "About"
},
"contact": {
"title": "Contact",
"nav": "Contact Us"
}
}
}
```
--------------------------------
### Wait for Locales in Sapper
Source: https://github.com/kaisermann/svelte-i18n/wiki/Home
Use the waitLocale function within a Sapper preload method to ensure dictionaries are loaded before the component renders.
```svelte
```
--------------------------------
### Set Initial and Fallback Locales (v1 vs v2)
Source: https://github.com/kaisermann/svelte-i18n/wiki/Migration
Illustrates the evolution of setting initial and fallback locales from v1's `getClientLocale` and `locale.set` to v2's consolidated `init` method. The `init` method simplifies configuration by accepting `fallbackLocale` and `initialLocale` options.
```javascript
import { getClientLocale, locale } from 'svelte-i18n'
locale.set(
getClientLocale({
fallback: 'en',
navigator: true,
})
)
```
```javascript
import { init } from 'svelte-i18n'
init({
fallbackLocale: 'en',
initialLocale: {
navigator: true,
},
})
```
--------------------------------
### Register Locale Dictionaries Asynchronously
Source: https://github.com/kaisermann/svelte-i18n/wiki/Home
Register loader functions to load dictionaries on demand. This improves performance by only loading the files required for the active locale.
```javascript
import { register } from 'svelte-i18n'
register('en', () => import('./en.json'))
register('en-US', () => import('./en-US.json'))
register('pt', () => import('./pt.json'))
```
--------------------------------
### Add Custom Formats (v1 vs v2)
Source: https://github.com/kaisermann/svelte-i18n/wiki/Migration
Compares the methods for adding custom formats. v1 used a dedicated `addCustomFormats` function, while v2 integrates this functionality into the `init` method via the `formats` option, allowing for a more centralized configuration.
```javascript
import { addCustomFormats } from 'svelte-i18n'
addCustomFormats({
number: {
EUR: { style: 'currency', currency: 'EUR' },
},
})
```
```javascript
import { init } from 'svelte-i18n'
init({
fallbackLocale: ...,
initialLocale, ...,
formats:{
number: {
EUR: { style: 'currency', currency: 'EUR' },
},
}
})
```
--------------------------------
### Add Locale Dictionaries Synchronously
Source: https://github.com/kaisermann/svelte-i18n/wiki/Home
Use the addMessages method to import and register translation dictionaries directly. This approach loads all dictionaries into memory immediately.
```javascript
import { addMessages } from 'svelte-i18n'
import en from './en.json'
import enUS from './en-US.json'
import pt from './pt.json'
addMessages('en', en)
addMessages('en-US', enUS)
addMessages('pt', pt)
```
--------------------------------
### Formatting Times with the $_.time Utility
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Illustrates the formatting of Date objects into locale-aware time strings using the $_.time utility. Examples include default formatting and using the 'medium' format option.
```html
```
--------------------------------
### Date, Time, and Number Formatters
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Provides functions to get Intl.DateTimeFormat and Intl.NumberFormat objects for localized formatting. These formatters can be configured with specific options and locales.
```APIDOC
## Date, Time, and Number Formatters
### Description
These functions allow you to obtain instances of `Intl.DateTimeFormat` and `Intl.NumberFormat` for locale-aware formatting of dates, times, and numbers. You can customize the formatting behavior using options and specify a locale.
### Method
`getDateFormatter`, `getTimeFormatter`, `getNumberFormatter`
### Endpoint
N/A (These are utility functions, not API endpoints)
### Parameters
#### `getDateFormatter` / `getTimeFormatter` Options
- **options** (`FormatterOptions`) - Required - An object containing formatting options for `Intl.DateTimeFormat`, including an optional `format` string and `locale`.
- **format** (string) - Optional - A specific format string to use.
- **locale** (string) - Optional - The locale to use for formatting (defaults to the current locale).
#### `getNumberFormatter` Options
- **options** (`FormatterOptions`) - Required - An object containing formatting options for `Intl.NumberFormat`, including an optional `format` string and `locale`.
- **format** (string) - Optional - A specific format string to use.
- **locale** (string) - Optional - The locale to use for formatting (defaults to the current locale).
### Request Example
```javascript
import { getDateFormatter, getTimeFormatter, getNumberFormatter } from 'svelte-i18n';
const dateFormatter = getDateFormatter({ year: 'numeric', month: 'long', day: 'numeric', locale: 'en-US' });
const timeFormatter = getTimeFormatter({ hour: '2-digit', minute: '2-digit', locale: 'en-US' });
const numberFormatter = getNumberFormatter({ style: 'currency', currency: 'USD', locale: 'en-US' });
console.log(dateFormatter.format(new Date()));
console.log(timeFormatter.format(new Date()));
console.log(numberFormatter.format(1234.56));
```
### Response
#### Success Response (200)
- **Intl.DateTimeFormat** - An instance of the `Intl.DateTimeFormat` object configured with the provided options.
- **Intl.NumberFormat** - An instance of the `Intl.NumberFormat` object configured with the provided options.
```
--------------------------------
### Localize App Content with svelte-i18n
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Getting Started.md
Localizes Svelte components by importing the `$format` method (aliased as `_`) and using it to translate message IDs. This example shows how to translate the page title and navigation links.
```svelte
{$_('page_title')}
```
--------------------------------
### Frontend Language Initialization in Layout
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Svelte-Kit.md
Sets the locale on the frontend using the browser's navigator.language within the SvelteKit layout load function. It also ensures svelte-i18n is initialized and waits for the locale to be ready. Requires '$app/environment', 'svelte-i18n', and '$types'.
```typescript
import {
browser
} from '$app/environment'
import '$lib/i18n' // Import to initialize. Important :)
import {
locale,
waitLocale
} from 'svelte-i18n'
import type {
LayoutLoad
} from './$types'
export const load: LayoutLoad = async () => {
if (browser) {
locale.set(window.navigator.language)
}
await waitLocale()
}
```
--------------------------------
### Formatting Date Parts with getDateFormatter
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Shows an example of using `getDateFormatter` to extract specific parts of a date object. This method is useful for custom date displays and manipulations.
```javascript
import { getDateFormatter } from 'svelte-i18n'
const getDateParts = date =>
getDateFormatter()
.formatToParts(date)
.filter(({ type }) => type !== 'literal')
.reduce((acc, { type, value }) => {
acc[type] = value
return acc
}, {})
getDateParts(new Date(2020, 0, 1)) // { month: '1', day: '1', year: '2020' }
```
--------------------------------
### Define Locale Dictionaries
Source: https://github.com/kaisermann/svelte-i18n/wiki/Home
Locale dictionaries are JSON objects containing key-value pairs for translations. These files serve as the source of truth for localized text in the application.
```json
// en.json
{
"page_title": "Page titlte",
"sign_in": "Sign in",
"sign_up": "Sign up"
}
// pt.json
{
"page_title": "Título da página",
"sign_in": "Entrar",
"sign_up": "Registrar"
}
```
--------------------------------
### JSON Message Definitions for svelte-i18n
Source: https://github.com/kaisermann/svelte-i18n/wiki/Dictionary
Examples of shallow and deep JSON structures for message dictionaries in svelte-i18n. These files define translations for different keys, supporting nested structures for better organization.
```json
{
"title": "Sign up",
"field.name": "Name",
"field.birth": "Date of birth",
"field.genre": "Genre"
}
```
```json
{
"title": "Sign up",
"field": {
"name": "Name",
"birth": "Date of birth",
"genre": "Genre"
}
}
```
--------------------------------
### Add Messages to Dictionary (v1 vs v2)
Source: https://github.com/kaisermann/svelte-i18n/wiki/Migration
Compares how dictionaries were added in v1 using `dictionary.set` and `dictionary.update` versus v2's `addMessages` method. v2 allows for merging messages by calling `addMessages` multiple times for the same locale.
```javascript
import { dictionary } from 'svelte-i18n'
dictionary.set({
en: { ... },
pt: { ... },
})
dictionary.update(d => {
d.fr = { ... }
return d
})
```
```javascript
import { addMessages } from 'svelte-i18n'
addMessages('en', { ... })
addMessages('pt', { ... })
addMessages('fr', { ... })
// message dictionaries are merged together
addMessages('en', { ... })
```
--------------------------------
### Basic Translation Usage in Svelte Component
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Svelte-Kit.md
Demonstrates how to use the svelte-i18n library within a Svelte component to display translated text. It imports the translation function '_' and uses it to render a placeholder string. Requires 'svelte-i18n'.
```svelte
{$_('my.translation.key')}
```
--------------------------------
### Interpolate values in Svelte templates
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Migration.md
Shows the change in syntax for passing interpolation values from a flat object in v1 to a nested 'values' property in v2.
```svelte
```
--------------------------------
### SSR Language Detection with Server Hook
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Svelte-Kit.md
Implements a SvelteKit server hook to detect the user's preferred language from the 'Accept-Language' header for SSR. It then sets the locale using svelte-i18n's locale store. Requires '@sveltejs/kit' and 'svelte-i18n'.
```typescript
import type {
Handle
} from '@sveltejs/kit'
import {
locale
} from 'svelte-i18n'
export const handle: Handle = async ({ event, resolve }) => {
const lang = event.request.headers.get('accept-language')?.split(',')[0]
if (lang) {
locale.set(lang)
}
return resolve(event)
}
```
--------------------------------
### Interpolate Values in Translations (v1 vs v2)
Source: https://github.com/kaisermann/svelte-i18n/wiki/Migration
Demonstrates the change in how interpolated values are passed to translation functions. In v1, values were passed as the second argument directly to `$format`. In v2, they are encapsulated within a `values` property.
```svelte
```
--------------------------------
### Use svelte-i18n formatters outside Svelte components
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/FAQ.md
This snippet shows how to access svelte-i18n formatters in non-Svelte files. It uses the 'unwrapFunctionStore' utility to subscribe to the store-based formatters, allowing direct invocation of formatting functions.
```javascript
import { unwrapFunctionStore, format, formatNumber } from 'svelte-i18n';
const $formatNumber = unwrapFunctionStore(formatNumber);
const $format = unwrapFunctionStore(format);
console.log(
$formatNumber(1000, 'en-US', { style: 'currency', currency: 'USD' }),
); // $1,000.00
console.log($format('Hello {name}', { name: 'John' }, 'en-US')); // Hello John
```
--------------------------------
### Initialization API
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
The `init` method configures the library's behavior, including fallback locales and initial locale settings. It must be called before setting a locale or rendering views.
```APIDOC
## POST /init
### Description
Initializes the svelte-i18n library with configuration options such as fallback locale, initial locale, custom formats, and message handling strategies.
### Method
POST
### Endpoint
/init
### Parameters
#### Request Body
- **fallbackLocale** (string) - Required - The global fallback locale.
- **initialLocale** (string | null) - Optional - The app's initial locale.
- **formats** (object) - Optional - Custom time, date, and number formats.
- **number**: Record
- **date**: Record
- **time**: Record
- **loadingDelay** (number) - Optional - Loading delay interval.
- **warnOnMissingMessages** (boolean) - Optional - Deprecated. Use `handleMissingMessage` instead.
- **handleMissingMessage** (function) - Optional - A method executed when a message is missing. May return a fallback string.
- **ignoreTag** (boolean) - Required - Whether to treat HTML/XML tags as string literals.
### Request Example
```json
{
"fallbackLocale": "en",
"initialLocale": "pt-br",
"formats": {
"number": {
"EUR": { "style": "currency", "currency": "EUR" }
}
},
"ignoreTag": false
}
```
### Response
#### Success Response (200)
- **void** - This method does not return a value.
#### Response Example
(No response body)
```
--------------------------------
### Initialize svelte-i18n with Options
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Getting Started.md
Initializes the svelte-i18n library after registering locale messages. The `init` function configures the fallback locale, initial locale (detected from the navigator), and other options. It's important to call this in your app's entry point.
```javascript
// src/i18n.js
import { register, init, getLocaleFromNavigator } from 'svelte-i18n';
register('en', () => import('./en.json'));
register('en-US', () => import('./en-US.json'));
register('pt', () => import('./pt.json'));
// en, en-US and pt are not available yet
init({
fallbackLocale: 'en',
initialLocale: getLocaleFromNavigator(),
});
// starts loading 'en-US' and 'en'
```
--------------------------------
### Formatting Dates with the $_.date Utility
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Explains how to format Date objects into locale-aware string representations using the $_.date utility. It shows basic usage and formatting with predefined options like 'medium'.
```html
```
--------------------------------
### Locale Detection Utilities
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
These utility methods help determine the initial locale based on various sources like hostname, pathname, navigator settings, query strings, or hash values.
```APIDOC
## GET /locale/from/hostname
### Description
Detects the locale from the hostname using a regular expression pattern.
### Method
GET
### Endpoint
/locale/from/hostname
### Parameters
#### Query Parameters
- **hostnamePattern** (RegExp) - Required - A regular expression to match against the hostname.
### Request Example
```js
import { getLocaleFromHostname } from 'svelte-i18n';
const locale = getLocaleFromHostname(/^(.*?)\./);
```
## GET /locale/from/pathname
### Description
Detects the locale from the pathname using a regular expression pattern.
### Method
GET
### Endpoint
/locale/from/pathname
### Parameters
#### Query Parameters
- **pathnamePattern** (RegExp) - Required - A regular expression to match against the pathname.
### Request Example
```js
import { getLocaleFromPathname } from 'svelte-i18n';
const locale = getLocaleFromPathname(/^\/(.*?)\/);
```
## GET /locale/from/navigator
### Description
Detects the locale from the browser's navigator settings.
### Method
GET
### Endpoint
/locale/from/navigator
### Parameters
(None)
### Request Example
```js
import { getLocaleFromNavigator } from 'svelte-i18n';
const locale = getLocaleFromNavigator();
```
## GET /locale/from/querystring
### Description
Detects the locale from a query string parameter.
### Method
GET
### Endpoint
/locale/from/querystring
### Parameters
#### Query Parameters
- **queryKey** (string) - Required - The key of the query parameter to look for.
### Request Example
```js
import { getLocaleFromQueryString } from 'svelte-i18n';
const locale = getLocaleFromQueryString('lang');
```
## GET /locale/from/hash
### Description
Detects the locale from the URL hash fragment.
### Method
GET
### Endpoint
/locale/from/hash
### Parameters
#### Query Parameters
- **hashKey** (string) - Required - The key within the hash fragment to extract the locale from.
### Request Example
```js
import { getLocaleFromHash } from 'svelte-i18n';
const locale = getLocaleFromHash('locale');
```
```
--------------------------------
### Initialize svelte-i18n configuration
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Configures global library behavior, including fallback locales and initial locale detection strategies. This must be invoked before setting a locale or rendering views.
```typescript
interface InitOptions {
fallbackLocale: string
initialLocale?: InitialLocaleOptions
formats?: Formats
loadingDelay?: number
}
```
```javascript
import { init } from 'svelte-i18n'
init({
fallbackLocale: 'en',
initialLocale: {
navigator: true,
},
})
```
--------------------------------
### Initialize svelte-i18n configuration
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
The init function configures global library settings including fallback locales, initial locales, and custom formatting rules. It must be called before any locale-dependent operations or view rendering.
```javascript
import { init } from 'svelte-i18n';
init({
fallbackLocale: 'en',
initialLocale: 'pt-br',
formats: {
number: {
EUR: { style: 'currency', currency: 'EUR' },
},
}
});
```
--------------------------------
### Set and Subscribe to Locale Changes in Regular Script
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Locale.md
Shows how to import the `locale` store from 'svelte-i18n' and use its `set` method to change the current locale. It also demonstrates subscribing to locale changes for logging purposes.
```javascript
import { locale } from 'svelte-i18n'
// Set the current locale to en-US
locale.set('en-US')
// This is a store, so we can subscribe to its changes
locale.subscribe(() => console.log('locale change'))
```
--------------------------------
### Wait for Locale Loading in Sapper
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Getting Started.md
Demonstrates how to use `waitLocale` in Sapper's `preload` method to ensure that locale dictionaries are loaded before rendering the application. This is crucial when using asynchronous loading of messages.
```svelte
```
--------------------------------
### Suppress Rollup 'THIS_IS_UNDEFINED' warning
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/FAQ.md
This snippet demonstrates how to configure the Rollup 'onwarn' handler to ignore specific warnings related to the 'intl-messageformat' package transpilation. It checks for the 'THIS_IS_UNDEFINED' code and suppresses it to keep the terminal output clean.
```javascript
const onwarn = (warning, onwarn) => {
if (
(warning.code === 'CIRCULAR_DEPENDENCY' &&
/[/\\]@sapper[/\\]/.test(warning.message))
) {
return
}
// ignores the annoying this is undefined warning
if(warning.code === 'THIS_IS_UNDEFINED') {
return
}
onwarn(warning)
}
export default {
client: {
onwarn,
},
server: {
onwarn,
},
}
```
--------------------------------
### Await locale loading
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Returns a promise that resolves when the specified locale's loader queue is complete. Useful for preloading data in SvelteKit or Sapper.
```svelte
```
--------------------------------
### Importing Dictionary Store in svelte-i18n
Source: https://github.com/kaisermann/svelte-i18n/wiki/Dictionary
Demonstrates how to import the dictionary store from the svelte-i18n library. This store is essential for managing all loaded message definitions for various locales within a Svelte application.
```javascript
import { dictionary } from 'svelte-i18n'
```
--------------------------------
### Basic Message Formatting with $format Store
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Demonstrates how to use the $format store (aliased as $_) to display localized messages within a Svelte component. It shows the basic usage of passing a message ID to the store.
```svelte
{$_('page_title')}
```
--------------------------------
### Applying Casing Utilities to Localized Messages
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Demonstrates the use of built-in casing utility functions provided by the $format store alias ($_) to transform localized messages into uppercase, lowercase, capitalized, or title case.
```html
{$_.upper('greeting.ask')}
{$_.lower('greeting.ask')}
{$_.capital('greeting.ask')}
{$_.title('greeting.ask')}
```
--------------------------------
### Define custom formats for Intl
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Allows defining custom styles for number, date, and time formatting using the Intl API. These formats can be referenced within components for consistent localization.
```javascript
import { init } from 'svelte-i18n'
init({
fallbackLocale: 'en',
formats: {
number: {
EUR: { style: 'currency', currency: 'EUR' },
},
},
})
```
```html
{$_.number(123456.789, { format: 'EUR' })}
```
--------------------------------
### Conditional Rendering Based on Loading State (Svelte)
Source: https://github.com/kaisermann/svelte-i18n/wiki/Locale
Illustrates how to use the `$loading` store in Svelte to conditionally render content while message definitions are being fetched. The UI displays 'Please wait...' when `$loading` is true, and the main content otherwise. Note that `$loading` is only true if fetching takes more than 200ms.
```svelte
{#if loading}
Please wait...
{:else}
{/if}
```
--------------------------------
### Access Date, Time, and Number Formatters
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
These functions return instances of Intl.DateTimeFormat or Intl.NumberFormat. They accept options that include standard Intl configuration along with optional format and locale overrides.
```typescript
import { getDateFormatter, getNumberFormatter, getTimeFormatter } from 'svelte-i18n';
type FormatterOptions = T & {
format?: string
locale?: string
}
const dateFmt = getDateFormatter({ locale: 'en-US' });
const timeFmt = getTimeFormatter({ format: 'short' });
const numFmt = getNumberFormatter({ style: 'currency', currency: 'USD' });
```
--------------------------------
### Locale Management
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
Functions for managing and retrieving locale information.
```APIDOC
## GET /getLocaleFromHash
### Description
Utility method to help getting an initial locale based on a hash `{key}={value}` string.
### Method
GET
### Endpoint
`/getLocaleFromHash`
### Parameters
#### Query Parameters
- **hashKey** (string) - Required - The key to look for in the hash string.
### Response
#### Success Response (200)
- **locale** (string) - The locale string extracted from the hash.
### Request Example
```js
import { getLocaleFromHash } from 'svelte-i18n';
const initialLocale = getLocaleFromHash('lang');
```
### Response Example
```json
{
"locale": "en"
}
```
```
```APIDOC
## POST /addMessages
### Description
Merge one or more dictionary of messages with the specified locale's dictionary.
### Method
POST
### Endpoint
`/addMessages`
### Parameters
#### Query Parameters
- **locale** (string) - Required - The locale to add messages to.
#### Request Body
- **dicts** (Dictionary[]) - Required - An array of message dictionaries to merge.
### Request Example
```js
import { addMessages } from 'svelte-i18n';
addMessages('en', { field_1: 'Name' });
addMessages('en', { field_2: 'Last Name' });
addMessages('pt', { field_1: 'Nome' });
addMessages('pt', { field_2: 'Sobrenome' });
```
### Response
#### Success Response (200)
- **status** (string) - Indicates successful addition of messages.
### Response Example
```json
{
"status": "Messages added successfully"
}
```
```
```APIDOC
## POST /register
### Description
Registers an async message `loader` for the specified `locale`. The loader queue is executed when changing to `locale` or when calling `waitLocale(locale)`.
### Method
POST
### Endpoint
`/register`
### Parameters
#### Query Parameters
- **locale** (string) - Required - The locale for which to register the message loader.
#### Request Body
- **loader** (function) - Required - An async function that returns a message dictionary object.
### Request Example
```js
import { register } from 'svelte-i18n';
register('en', () => import('./_locales/en.json'));
register('pt', () => import('./_locales/pt.json'));
```
### Response
#### Success Response (200)
- **status** (string) - Indicates successful registration of the message loader.
### Response Example
```json
{
"status": "Message loader registered successfully"
}
```
```
```APIDOC
## POST /waitLocale
### Description
Executes the queue of `locale`. If the queue isn't resolved yet, the same promise is returned. Great to use in the `preload` method of Sapper for awaiting [`loaders`](/svelte-i18n/blob/master/docs#22-asynchronous).
### Method
POST
### Endpoint
`/waitLocale`
### Parameters
#### Query Parameters
- **locale** (string) - Optional - The locale to wait for. Defaults to the current locale.
### Response
#### Success Response (200)
- **status** (string) - Indicates that the locale queue has been resolved.
### Request Example
```js
import { waitLocale } from 'svelte-i18n';
// In a Sapper preload function:
await waitLocale();
```
### Response Example
```json
{
"status": "Locale queue resolved"
}
```
```
--------------------------------
### Accessing svelte-i18n Formatters Directly
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Formatting.md
Demonstrates importing and using low-level formatter functions from 'svelte-i18n'. These functions allow for direct manipulation and formatting of dates, numbers, times, and messages, offering greater flexibility than the default options.
```javascript
import {
getDateFormatter,
getNumberFormatter,
getTimeFormatter,
getMessageFormatter,
} from 'svelte-i18n';
```
```javascript
import { getDateFormatter } from 'svelte-i18n';
const getDateParts = (date) =>
getDateFormatter()
.formatToParts(date)
.filter(({ type }) => type !== 'literal')
.reduce((acc, { type, value }) => {
acc[type] = value;
return acc;
}, {});
getDateParts(new Date(2020, 0, 1)); // { month: '1', day: '1', year: '2020' }
```
--------------------------------
### Initialize locale from URL hash
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
Uses getLocaleFromHash to extract the initial locale from a URL hash parameter. This is useful for setting the application locale based on URL state during initialization.
```javascript
import { init, getLocaleFromHash } from 'svelte-i18n';
init({
fallbackLocale: 'en',
initialLocale: getLocaleFromHash('lang'),
});
```
--------------------------------
### Formatting Numbers with the $_.number Utility
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Demonstrates how to format numerical values according to locale-specific conventions using the $_.number utility. It shows default formatting and formatting with a specified locale ('pt').
```html
{$_.number(100000000)}
{$_.number(100000000, { locale: 'pt' })}
```
--------------------------------
### Importing svelte-i18n Formatters
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Demonstrates how to import various formatter functions from the 'svelte-i18n' library. These functions allow for direct manipulation and formatting of different data types.
```javascript
import {
getDateFormatter,
getNumberFormatter,
getTimeFormatter,
getMessageFormatter
} from 'svelte-i18n'
```
--------------------------------
### Message Formatter
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Retrieves an instance of IntlMessageFormat for formatting complex messages with placeholders and pluralization rules.
```APIDOC
## Message Formatter
### Description
This function returns an instance of `IntlMessageFormat`, which is used for formatting messages that may contain placeholders, pluralization, or other complex internationalization features.
### Method
`getMessageFormatter`
### Endpoint
N/A (This is a utility function, not an API endpoint)
### Parameters
- **messageId** (string) - Required - The identifier for the message to be formatted.
- **locale** (string) - Required - The locale for which to format the message.
### Request Example
```javascript
import { getMessageFormatter } from 'svelte-i18n';
// Assuming you have a message defined like: 'welcome_message': 'Hello, {name}! You have {count, plural, one {one message} other {# messages}}.'
const formatter = getMessageFormatter('welcome_message', 'en-US');
console.log(formatter.format({ name: 'Alice', count: 1 })); // Output: Hello, Alice! You have one message.
console.log(formatter.format({ name: 'Bob', count: 5 })); // Output: Hello, Bob! You have 5 messages.
```
### Response
#### Success Response (200)
- **IntlMessageFormat** - An instance of the `IntlMessageFormat` object, ready to format messages for the specified locale.
```
--------------------------------
### Internationalization Formatters
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
Functions for accessing built-in internationalization formatters.
```APIDOC
## GET /getDateFormatter
### Description
Returns an instance of `Intl.DateTimeFormat` for date formatting.
### Method
GET
### Endpoint
`/getDateFormatter`
### Parameters
#### Query Parameters
- **options** (FormatterOptions) - Required - Options for formatting, including `format` and `locale`.
### Response
#### Success Response (200)
- **formatter** (Intl.DateTimeFormat) - An instance of `Intl.DateTimeFormat`.
### Request Example
```js
import { getDateFormatter } from 'svelte-i18n';
const dateFormatter = getDateFormatter({ locale: 'en-US', format: 'long' });
console.log(dateFormatter.format(new Date()));
```
### Response Example
```json
{
"formatter": "[Intl.DateTimeFormat object]"
}
```
```
```APIDOC
## GET /getTimeFormatter
### Description
Returns an instance of `Intl.DateTimeFormat` for time formatting.
### Method
GET
### Endpoint
`/getTimeFormatter`
### Parameters
#### Query Parameters
- **options** (FormatterOptions) - Required - Options for formatting, including `format` and `locale`.
### Response
#### Success Response (200)
- **formatter** (Intl.DateTimeFormat) - An instance of `Intl.DateTimeFormat`.
### Request Example
```js
import { getTimeFormatter } from 'svelte-i18n';
const timeFormatter = getTimeFormatter({ locale: 'en-US', format: 'short' });
console.log(timeFormatter.format(new Date()));
```
### Response Example
```json
{
"formatter": "[Intl.DateTimeFormat object]"
}
```
```
```APIDOC
## GET /getNumberFormatter
### Description
Returns an instance of `Intl.NumberFormat` for number formatting.
### Method
GET
### Endpoint
`/getNumberFormatter`
### Parameters
#### Query Parameters
- **options** (FormatterOptions) - Required - Options for formatting, including `style` and `locale`.
### Response
#### Success Response (200)
- **formatter** (Intl.NumberFormat) - An instance of `Intl.NumberFormat`.
### Request Example
```js
import { getNumberFormatter } from 'svelte-i18n';
const numberFormatter = getNumberFormatter({ locale: 'en-US', style: 'currency' });
console.log(numberFormatter.format(12345.67));
```
### Response Example
```json
{
"formatter": "[Intl.NumberFormat object]"
}
```
```
```APIDOC
## GET /getMessageFormatter
### Description
Returns an instance of `IntlMessageFormat` for message formatting.
### Method
GET
### Endpoint
`/getMessageFormatter`
### Parameters
#### Query Parameters
- **messageId** (string) - Required - The ID of the message to format.
- **locale** (string) - Required - The locale for which to format the message.
### Response
#### Success Response (200)
- **formatter** (IntlMessageFormat) - An instance of `IntlMessageFormat`.
### Request Example
```js
import { getMessageFormatter } from 'svelte-i18n';
const messageFormatter = getMessageFormatter('welcome_message', 'en');
console.log(messageFormatter.format({ name: 'User' }));
```
### Response Example
```json
{
"formatter": "[IntlMessageFormat object]"
}
```
```
--------------------------------
### Message Formatting with Options Object
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Illustrates the structure of the MessageObject used with the $format store for advanced message formatting. This includes specifying message ID, locale, default values, format types, and interpolation values.
```typescript
interface MessageObject {
id?: string;
locale?: string;
format?: string;
default?: string;
values?: Record;
}
```
--------------------------------
### Detect locale from browser environment
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
Utility functions to extract the initial locale from various browser sources such as hostname, pathname, navigator settings, or query parameters.
```javascript
import { getLocaleFromHostname, getLocaleFromPathname, getLocaleFromNavigator, getLocaleFromQueryString } from 'svelte-i18n';
const hostLocale = getLocaleFromHostname(/^(.*?)\./);
const pathLocale = getLocaleFromPathname(/^\/(.*?)\//);
const navLocale = getLocaleFromNavigator();
const queryLocale = getLocaleFromQueryString('lang');
```
--------------------------------
### Set and Subscribe to Locale Changes (JavaScript)
Source: https://github.com/kaisermann/svelte-i18n/wiki/Locale
Demonstrates how to set the current locale and subscribe to its changes using the `locale` store in a regular JavaScript environment. This is useful for global locale management outside of Svelte components.
```javascript
import { locale } from 'svelte-i18n'
// Set the current locale to en-US
locale.set('en-US')
// This is a store, so we can subscribe to its changes
locale.subscribe(() => console.log('locale change'))
```
--------------------------------
### Await locale loading in Svelte
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Methods.md
Uses waitLocale within a Svelte component's module context to ensure all asynchronous message loaders are resolved before the component renders.
```svelte
```
--------------------------------
### Extract translation messages via CLI
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/CLI.md
The extract command parses Svelte components based on a glob pattern to generate a translation file. It supports options for shallow object creation, file overwriting, and custom configuration paths.
```bash
$ svelte-i18n extract [options] [output-file]
```
--------------------------------
### Register Locale Messages Asynchronously
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Getting Started.md
Registers loader functions for locale messages, allowing for asynchronous loading. This improves performance by only loading dictionaries when needed. The `register` function takes a locale and a function that returns a Promise resolving to the message dictionary.
```javascript
// src/i18n.js
import { register } from 'svelte-i18n';
register('en', () => import('./en.json'));
register('en-US', () => import('./en-US.json'));
register('pt', () => import('./pt.json'));
// en, en-US and pt are not available yet
```
--------------------------------
### Register asynchronous locale loaders
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Registers an async loader function for a specific locale. The loader is executed when the locale is requested or via waitLocale.
```javascript
import { register } from 'svelte-i18n'
register('en', () => import('./_locales/en.json'))
register('pt', () => import('./_locales/pt.json'))
```
--------------------------------
### Format Dates with $date in Svelte
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Formatting.md
The $date store formats a Date object into a string using specified formats. It leverages formatjs for localization. Refer to the formats section for available format options.
```svelte
```
--------------------------------
### Accessing Nested Messages via Dot Notation
Source: https://github.com/kaisermann/svelte-i18n/wiki/Formatting
Shows how to access localized messages that are nested within a JSON dictionary using dot notation for the message ID. This simplifies referencing deeply structured translations.
```json
// en.json
{
"shallow.prop": "Shallow property",
"deep": {
"property": "Deep property"
}
}
```
```svelte
{$_('shallow.prop')}
{$_('deep.prop')}
```
--------------------------------
### Define Locale Dictionaries
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Getting Started.md
Defines locale dictionaries in JSON format for different languages. These files contain key-value pairs where keys are message identifiers and values are the translated strings.
```json
// en.json
{
"page_title": "Page title",
"sign_in": "Sign in",
"sign_up": "Sign up"
}
// pt.json
{
"page_title": "Título da página",
"sign_in": "Entrar",
"sign_up": "Registrar"
}
```
--------------------------------
### Add message dictionaries
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Merges one or more message dictionaries into a specific locale. This is used to populate the translation store with key-value pairs.
```javascript
addMessages('en', { field_1: 'Name' })
addMessages('en', { field_2: 'Last Name' })
addMessages('pt', { field_1: 'Nome' })
addMessages('pt', { field_2: 'Sobrenome' })
```
--------------------------------
### Display Content Based on Loading State in Svelte Component
Source: https://github.com/kaisermann/svelte-i18n/blob/main/docs/Locale.md
Illustrates how to use the `$isLoading` store from 'svelte-i18n' within a Svelte component to conditionally render content. This is useful for showing loading indicators while message definitions are being fetched.
```svelte
{#if $isLoading}
Please wait...
{:else}
{/if}
```
--------------------------------
### Retrieve Message Formatter
Source: https://github.com/kaisermann/svelte-i18n/wiki/Methods
Retrieves an instance of IntlMessageFormat for a specific message identifier and locale. This is used for advanced message processing outside of standard component bindings.
```typescript
import { getMessageFormatter } from 'svelte-i18n';
const formatter = getMessageFormatter('my-message-id', 'en-US');
```