kaisermann / svelte-i18n

Internationalization library for Svelte

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use translation inside script area

Spaceman2019 opened this issue · comments

Hi,
I want to store a translation in a variable to pass it to a component. How can I do this? I haven't found an example of this.
Thanks

Hey, @Spaceman2019 👋 There are a few ways to do this. One is to subscribe to the _/t/format store:

import { format } from 'svelte-i18n`

let localFormat

format.subscribe(value => (localFormat = value))

localFormat('home.page.title')

If it's not a code hot path, you can use the get function from 'svelte/store' to use the _ function outside of a svelte context:

import { get } from 'svelte/store'
import { _ } from 'svelte-i18n`

console.log(get(_)('home.page.title'))

Hello,

I was trying to do the same.
I'm using typescript.
I can't type the "localFormat" as MessageFormatter since it's not exported from the library.
Exporting types would be great if possible.

Thanks

I had a different idea and exposed a method in v3.6.0 called unwrapFunctionStore to help with my first suggestion:

// some-file.js
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

Also added this to the FAQ section

Thank you, it's very convenient.