Let's say we have an Array in our translations file
en.js
section: {
title: 'This value is a string and it works just fine',
highlighted: [
{
title: 'Highlighted title 1',
text: 'Highlighted text 1'
},
{
title: 'Highlighted title 2',
text: 'Highlighted text 2'
}
]
}
With Nuxt version 2 and nuxt-i18n
it was possible to do:
<h2>{{ $t('section.title') }}</h2>
<template v-for="(item, index) in $t('section.highlighted')" :key="item.title">
{{ item.title }}
{{ item.text }}
</template>
but since I upgraded to Nuxt v3 and @nuxtjs/i18n
the array $t('section.highlighted')
outputs the key
s
e
c
t
i
o
n
.
h
i
g
h
l
i
g
h
t
e
d
this is my plugin setup in nuxt.config.js
modules: [
'@nuxtjs/i18n',
],
i18n: {
locales: ['en', 'de'],
defaultLocale: 'en',
vueI18n: {
legacy: false,
fallbackLocale: 'en',
messages: {
en,
de
}
}
},
What am I missing? I can't find anything about it in the migration guide https://i18n.nuxtjs.org/migrating
CodePudding user response:
You try to use this tool in the wrong way. I18n tool is only to get some translation string by key, not to store some kind of data like arrays.
You can arrange it this way:
en.js
section: {
title: 'My title',
highlighted: {
// '1' - just key
'1': {
title: 'Highlighted title 1',
text: 'Highlighted text 1'
},
'2': {
title: 'Highlighted title 2',
text: 'Highlighted text 2'
}
]
}
component.vue
<template>
<div> {{ $t('section.highlighted.1.title') }} </div>
</template>
Maybe it can be a good idea with translating if you have fixed k
-elements to translate, that's ok (for a landing page's blocks - ended features list, etc).
But if you want to show big data here, you should take a look at a database and store your data there or in JSON files on the client side and get them manually by your locale (this.$i18n.locale
).
CodePudding user response:
You totally can iterate on an array in your translation files, vue-i18n has specific methods to achieve that.
https://vue-i18n.intlify.dev/api/composition.html#composer
Since nuxt/i18n for nuxt 3 is using this version of vue i18n, you can use them directly like so:
<p
v-for="paragraph in $tm('some.array')"
:key="paragraph"
>
{{ $rt(paragraph) }}
</p>