Add RTL condition in head with Nuxt Js i18n

Viewed 1410

I would like to add a condition as follows

if(app.i18n.locale == 'ar')

I use Arabic with English in this project. If the current language is Arabic, bootstrap-rtl.css is added in the head, and if the current language en is called bootstrap.css, I have tried more than one method and did not succeed.

1 Answers

Add a file in plugins folder for example direction-control.js

    export default ({ app }, inject) => {
    const dir = () =>
      app.i18n.locales.find((x) => x.code === app.i18n.locale)?.dir;
      inject('dir', dir);
    };

While your nuxt.config.js will need similar code to this

  plugins: [
      '~/plugins/direction-control',  // your plugins file name
      // other plugins
    ],
    modules: [
    [
      'nuxt-i18n',
      {
        locales: [
          {
            code: 'en',
            file: 'en.json',
            dir: 'ltr',
            name: 'English',
          },
          {
            code: 'ar',
            file: 'ar.json',
            dir: 'rtl',        // that will be passed to your app
            name: 'عربي',
          },
        ],
        langDir: 'translations/',
        defaultLocale: 'ar',
      },
    ],
  ],

Now it's time to get dir

export default {
  mounted() {
    console.log(this.$dir()); // logs your direction 'ltr' or 'rtl'
    console.log(this.$i18n.locale);
    if (this.$i18n.locale == "ar") {
       // make some action
    }
  },
}

or inside template like this

<template>
  <div :dir="$dir()">
    <Nuxt />
  </div>
</template>
Related