Skip to content

Custom slot name braces #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jun 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,66 @@ const term = computed(() => t("insurance"));
</template>
```

### Translation component

```vue
<i18n>
{
"en": {
"message": "Open the {faq-link} page."
"faq": "FAQ"
},
}
</i18n>

<template>
<TranslationComponent :translation="$t('message')">
<template #faq-link>
<router-link :to="FAQ_ROUTE">
{{ $t('faq') }}
</router-link>
</template>
</TranslationComponent>
</template>
```

#### Custom slot values

Custom slot values may be useful when default braces (`{` and `}`) are wrongly treated by the
[Locize](https://github.com/locize/i18next-locize-backend) service or don't satisfy other needs.

Use custom values for recognizing start and end of the insertion point of the `TranslationComponent`
inside localization term:
```js
// main.js
app.use(I18NextVue, {
i18next,
slotStart: '<slot>',
slotEnd: '</slot>',
});
```
```vue
<!-- Component.vue -->
<i18n>
{
"en": {
"message": "Open the <slot>faq-link</slot> page."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cool... similar to react-i18next named tags => https://react.i18next.com/latest/trans-component
image

"faq": "FAQ"
},
}
</i18n>

<template>
<TranslationComponent :translation="$t('message')">
<template #faq-link>
<router-link :to="FAQ_ROUTE">
{{ $t('faq') }}
</router-link>
</template>
</TranslationComponent>
</template>
```

## Contributing

### Requirements
Expand Down
33 changes: 26 additions & 7 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,19 @@ declare module 'vue' {
interface VueI18NextOptions {
i18next: i18n;
rerenderOn?: ('languageChanged' | 'loaded' | 'added' | 'removed')[];
// Optional custom pattern for matching slot start of the `TranslationComponent.`
slotStart?: string,
// Optional custom pattern for matching slot end of the `TranslationComponent`.
slotEnd?: string,
}

let slotPattern: RegExp;

export default function install(app: App, {
i18next,
rerenderOn = ['languageChanged', 'loaded', 'added', 'removed'],
slotStart = '{',
slotEnd = '}',
}: VueI18NextOptions): void {
const genericT = i18next.t.bind(i18next);
// the ref (internally) tracks which Vue instances use translations
Expand Down Expand Up @@ -116,6 +124,8 @@ export default function install(app: App, {
}
});

slotPattern = slotNamePattern(slotStart, slotEnd);

/** Translation function respecting lng and ns. The namespace can be overriden in $t calls using a key prefix or the 'ns' option. */
function getTranslationFunction(lng?: string, ns?: string[]): TFunction {
if (lng) {
Expand Down Expand Up @@ -161,19 +171,28 @@ export default function install(app: App, {
}

export function useTranslation() {
const instance = getCurrentInstance();
if (!instance) {
throw new Error("i18next-vue: No Vue instance in context. Make sure to register the i18next-vue plugin using app.use(...).");
}
const instance = currentInstance();
const globalProps = instance.appContext.config.globalProperties;
return {
i18next: globalProps.$i18next as i18n,
t: globalProps.$t.bind(instance.proxy) as SimpleTFunction
}
}

function currentInstance() {
const instance = getCurrentInstance();
if (!instance) {
throw new Error("i18next-vue: No Vue instance in context. Make sure to register the i18next-vue plugin using app.use(...).");
}
return instance;
}

// pattern matches '{ someSlot }'
const slotNamePattern = new RegExp('{\\s*([a-z0-9\\-]+)\\s*}', 'gi');
function slotNamePattern(start: string, end: string) {
const pattern = `${start}\\s*([a-z0-9\\-]+)\\s*${end}`;
return new RegExp(pattern, 'gi');
}

export const TranslationComponent = defineComponent({
props: {
"translation": {
Expand All @@ -188,15 +207,15 @@ export const TranslationComponent = defineComponent({

let match;
let lastIndex = 0;
while ((match = slotNamePattern.exec(translation)) !== null) {
while ((match = slotPattern.exec(translation)) !== null) {
result.push(translation.substring(lastIndex, match.index))
const slot = slots[match[1]];
if (slot) {
result.push(...slot());
} else {
result.push(match[0]);
}
lastIndex = slotNamePattern.lastIndex;
lastIndex = slotPattern.lastIndex;
}
result.push(translation.substring(lastIndex))
return result;
Expand Down