Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active October 26, 2022 18:34
Show Gist options
  • Save daliborgogic/14a7bb7fb2d1b0f588b5cfb940c6c1ed to your computer and use it in GitHub Desktop.
Save daliborgogic/14a7bb7fb2d1b0f588b5cfb940c6c1ed to your computer and use it in GitHub Desktop.
[POC] i18n in 142 bytes πŸ’₯
export default function (locale, path, ...args) {
return (path, ...args) => {
const keys = path.trim().split('.')
const fn = keys.reduce((prev, curr) => prev && prev[curr], locale)
return typeof fn === 'function' ? fn(...args) : fn
}
}
// export default function(t,e,...n){return(e,...n)=>{const r=e.trim().split(".").reduce((t,e)=>t&&t[e],t);return"function"==typeof r?r(...n):r}}
@daliborgogic
Copy link
Author

daliborgogic commented Nov 6, 2021

<script setup>
import useI18n from './i18n.js'
let locale = $ref('de')

let i18n = $ref({
  en: {
    welcome: 'Welcome!',
    hello: x => `Hello ${x}!`,
    colors: [
      'White',
      'Black'
    ]
  },
  de: {
    welcome: 'Willkommen!',
    hello: x => `Hallo ${x}!`,
    colors: [
      'Weiß',
      'Schwarz'
    ]
  }
}) 

const t = useI18n(i18n[locale])
</script>

<template>
{{ locale }} <!-- de -->
{{ 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