Created
June 13, 2023 15:09
-
-
Save notflip/f8e2ccb33b672179995947a10aa684d1 to your computer and use it in GitHub Desktop.
Nuxt Directus Translations with Language fallback per field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="bg-slate-200"> | |
<h1 class="text-3xl" v-html="getFieldWithLanguageFallback('headline')"></h1> | |
<div v-html="getFieldWithLanguageFallback('content')"></div> | |
</div> | |
</template> | |
<script setup lang="ts"> | |
const { locale } = useI18n({ inheritLocale: true }) | |
const { data } = defineProps<{ | |
data: object, | |
}>() | |
// Sort data so the current language is first in the array, in the next step we loop it until we hit a translation | |
const filteredData = computed(() => { | |
data.translations = data.translations.sort(a => a.languages_id === locale.value ? -1 : 1) | |
return data | |
}) | |
const getFieldWithLanguageFallback = (field) => { | |
for (const data of filteredData.value.translations) { | |
if (data[field]) { | |
return data[field] | |
} | |
} | |
} | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<component | |
v-for="(block, i) in filteredBlocks" | |
:key="`${block.collection}-${i}`" | |
:is="components[block.collection]" | |
:data="block.item" | |
/> | |
</div> | |
</template> | |
<script setup lang="ts"> | |
const { $directus } = useNuxtApp() | |
const { t, i18n } = useI18n({ inheritLocale: true }) | |
const localePath = useLocalePath() | |
const components = { | |
block_hero: resolveComponent('block_hero') | |
} | |
const { data: page } = await useAsyncData('global', () => { | |
return $directus.items('pages').readOne('13aafd76-XXXXX', { | |
fields: ['*', 'blocks.*', 'blocks.item.*', 'blocks.item.translations.*'], | |
}) | |
}) | |
const filteredBlocks = computed(() => { | |
return !Array.isArray(page.value?.blocks) ? [] : page.value?.blocks | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment