FluentContext

The FluentContext object exposes localization functions via the svelte context. It’s used internally by the Localized and Overlay components. It can also be retrieved with getFluentContext and used directly.

FluentContext.localize

The FluentContext.localize function allows you to use localizations in component scripts. This can be useful when interacting with browser APIs or third-party libraries.

Using the Localized and getFluentContext components is the preferred way to localize your application with svelte-fluent. The FluentContext.localize function provides additional flexibility in situations where using the components would not be feasible.

const { localize } = getFluentContext();
const text = localize(id, args);

Parameters

NameTypeDefaultDescription
idstringundefinedUnique identifier for the translation
argsRecord<string, FluentVariable>undefinedArguments for interpolation

Return value

The localized message as a string.

Static text example

<script>
	import { getFluentContext } from '@nubolab-ffwd/svelte-fluent';
	const { localize } = getFluentContext();
</script>

<button onclick={() => window.alert(localize('hello'))}>Say hello</button>
en.ftl
hello = Hello, world!
Result:

Dynamic text with variables example

<script>
	import { getFluentContext } from '@nubolab-ffwd/svelte-fluent';
	const { localize } = getFluentContext();
	const name = 'World';
</script>

<button onclick={() => window.alert(localize('hello', { name }))}>Say hello</button>
en.ftl
hello = Hello, {$name}!
Result:

Attributes example

You can reference attributes of a translation message by calling localize with both identifiers joined with a period.

In the example below this is done for the .default attribute of the prompt message by calling localize with 'prompt.default' as the message identifier.

<script>
	import { getFluentContext } from '@nubolab-ffwd/svelte-fluent';
	const { localize } = getFluentContext();
</script>

<button onclick={() => window.prompt(localize('prompt'), localize('prompt.default'))}>
	Show prompt
</button>
en.ftl
prompt = Please enter your name
	.default = Your name goes here
Result: