Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active October 14, 2024 22:38
Show Gist options
  • Save daliborgogic/1b3b7468d1afb8a67bcab7ca2091a705 to your computer and use it in GitHub Desktop.
Save daliborgogic/1b3b7468d1afb8a67bcab7ca2091a705 to your computer and use it in GitHub Desktop.
132 bytes i18n in Nuxt.js
// export function useI18n(translations) {
// return (key, ...args) => {
// const value = key.trim().split('.').reduce((obj, k) => obj?.[k], translations) ?? key
// return typeof value === 'function' ? value(...args) : value
// }
// }
export function useI18n(t){return(n,...e)=>{const r=n.trim().split('.').reduce(((t,n)=>t?.[n]),t)??n;return'function'==typeof r?r(...e):r}}
export const t = (x, y) => useRoute().meta.t(x, y)
@daliborgogic
Copy link
Author

daliborgogic commented Oct 9, 2024

Usage

export default defineNuxtRouteMiddleware(async (to) => {
  const { lang } = to.params
  const isLang = ['sr', 'de'].includes(lang)
  const filename = isLang ? lang : 'en'
  const { default: i18n } = await import(`./../i18n/${to.name}/${filename}.js`)
  // DE
  // {
  //  welcome: 'Willkommen!',
  //  hello: x => `Hallo ${x}!`,
  //  colors: [
  //    'Weiß',
  //    'Schwarz'
  //  ]
  // }
  to.meta = { t: useI18n(i18n) }
})
<script setup>
// No imports; Magic 🪄
</script>

<template>
{{ t('welcome') }}   <!-- Willkommen! -->
{{ t('hello', 'Dalibor') }}  <!-- Hallo Dalibor! -->
{{ t('colors.1') }}  <!-- Schwarz -->
</template>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment