Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamic dir and locale in HtmlAttr in Nuxt3?

I'm using @nuxtjs/i18n plugin with nuxt 3 and after I install it I wrote my i18n(config) in the nuxt.config.ts my code:

  i18n: {
    locales: [
        {
            code: 'fa',
            iso: 'fa-IR',
            name: 'Farsi',
            file: 'fa-IR.json',
            dir: 'rtl',
        },
        {
            code: 'en',
            iso: 'en-US',
            name: 'English',
            file: 'en-US.json',
            dir: 'ltr',
        },
    ],
    defaultLocale: 'fa',
    detectBrowserLanguage: false,
    langDir: "lang",
    vueI18n: {
        legacy: false,
        fallbackLocale: 'fa',
    }
}

after that, I use useLocaleHead({}) and useHead({}) in the default.vue(it's in my layout actually)

<script setup lang="ts">

const head = useLocaleHead({
  addDirAttribute: true,
  addSeoAttributes: true
});
useHead({
 htmlAttrs: {
   lang: head.value.htmlAttrs!.lang,
   dir: head.value.htmlAttrs!.dir
 },
});
</script>

but, when I run the project the dir and locale won't dynamic and change if I select another language. the output images: enter image description here enter image description here

as you can see dir and lang attributes on html tag won't change. however, the content's shown as english.
can anyone help how I can develop it with nuxt3??

like image 270
AmirrezaJM Avatar asked Oct 24 '25 14:10

AmirrezaJM


2 Answers

I had the same problem and I solved it using <Html> tag in my layout file:

This is the content of my layouts\default.vue file

<template>
  <div>
    <Html :lang="head.htmlAttrs.lang" :dir="head.htmlAttrs.dir"></Html>
    <Navbar />
    <div class="content">
      <slot />
    </div>
  </div>
</template>

<script setup>
const head = useLocaleHead({
  addDirAttribute: true,
  identifierAttribute: 'id',
  addSeoAttributes: true
})
</script>

I hope it solved your problem

like image 192
Ali Azimi Avatar answered Oct 27 '25 02:10

Ali Azimi


The short answer is just to add an html tag to your layouts/default file

<template>
   <Html :lang="head.htmlAttrs.lang" :dir="head.htmlAttrs.dir">
    ... the rest of your code in layouts/default
  </Html>
</template>

<script setup>
const head = useLocaleHead({
  addDirAttribute: true,
  identifierAttribute: 'id',
  addSeoAttributes: true
})
</script>
like image 28
Hadi Majidi Avatar answered Oct 27 '25 03:10

Hadi Majidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!