JMK
JMK

Reputation: 28059

Setting the language attribute when using i18n and Nuxt?

With Nuxt, you can set the language HTML attribute inside the nuxt.config.js file like so:

module.exports = {
  head: {
    htmlAttrs: {
      lang: 'en-GB',
},
... etc etc

However, what should you do if you have a multi-language app? Is there any way to set the language attribute based on the locale?

I thought that maybe document.documentElement.setSttribute('lang', 'language-code') would work, but as nuxt is rendered server side, it doesn't seem to have access to the documentElement object.

Thanks

Upvotes: 7

Views: 13195

Answers (3)

fidgital
fidgital

Reputation: 81

If you're using nuxt-i18n, you can call $nuxtI18nHead with addSeoAttributes: true in your default layout. This will set the lang attribute as well as some other language-specific header attributes for better SEO.

export default {
    head() {
        return this.$nuxtI18nHead({ addSeoAttributes: true })   
    },
}

Source: https://i18n.nuxtjs.org/seo#improving-performance

Upvotes: 3

s0up
s0up

Reputation: 422

Maybe I'm late, but it's just as simple as this chunk of code in your layouts/default.vue:

export default {
    // other code...
    head() {
        return {
            htmlAttrs: {
                lang: this.$i18n.locale
            }
        }
    },
    // other code...
}

Upvotes: 14

Sk_
Sk_

Reputation: 1191

  1. Install vue-i18n npm
 npm install vue-i18n
  1. create a plugin in the plugin dir and add the below code. Eg: i18n.js
import Vue from 'vue' 

import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export default ({app}) => {
    app.i18n = new ueI18n({
        locate: 'ja',
        fallbackLocale: 'en',
        silentTranslationWarn: true,
        message: {
            'ja': require('~/locale/ja/translations.json'),
             'en': require('~/locale/en/translations.json')
        }
    })
}
  1. Include this plugin in your nuxt.config.js file and set the lang
module.exports = {
    plugins: [{src: '~plugins/i18n.js', injectAs: 'i18n'}],
    head: {
        htmlAttrs: {
            lang: this.$i18n.locale,
        }
    }
}
  1. translations.json file contain your translation in json format
{
    "hello": "Hello World"
}
  1. In component file, you can access the translation as below
<p>{{ $t("hello") }}</p>

Note: I didnt tested the code

Upvotes: 2

Related Questions