Giter Site home page Giter Site logo

gridsome-plugin-i18n's Introduction

gridsome-plugin-i18n's People

Contributors

cfecherolle avatar daaru00 avatar giuseppeaiello avatar sebj54 avatar sebtiz13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

gridsome-plugin-i18n's Issues

Provide better example using page queries

Describe the bug
Trying to use gridsome-plugin-i18n with page-query but I got an error

To Reproduce
After configure gridsome-plugin-i18n create any page using page-query applying lang filter as shown on README.

query($locale:String) {
  careers: allCareer(lang: $locale, sortBy: "order", order: ASC) {
    edges {
      node {
        title
        content
        id
      }
    }
  }
}

Expected behavior
Query execute without error

Environment (please complete the following information):

  • OS: Ubuntu
  • NodeJS Version [v12.16.3]
  • Gridsome Version Version [0.7.14]
  • Browser [chrome]
  • Plugin Version [1.3.0]

Plugin configuration

{
  use: 'gridsome-plugin-i18n',
  options: {
    locales: ['en-us', 'pt-br'],
    pathAliases: {
      'en-us': 'en',
      'pt-br': 'pt'
    },
    fallbackLocale: 'pt',
    defaultLocale: 'pt',
    messages: {}
  }
}

How to properly query data with graphql

Hello,
I'm trying to query data based on locale:

<div v-if="$i18n.locale === 'en'">
{{edge.node.nameEn}}
</div>

<div v-if="$i18n.locale === 'nl'">
{{edge.node.nameNl}}
</div> 

<page-query>
  query {
    people: allPeople {
      edges {
        node {
          nameEn
          nameNl 
          DescEn
          DescNl
        }
      }
    }
  }
</page-query>

This works for me, but I have a feeling it's a bit hardcoded and also memory consuming as it loads both locales in one page load. Maybe there's a prettier way to query data based on locale?

P.S. I'm querying data from Airtable, so data structure (nameEn, nameNl) probably can't be changed.

P.S. in readme there's notion that your data source need to support query based on locale. But there's no detailed information what that means. Maybe you had some more info about that?

Thanks!

Duplicate key for property path

Describe the bug

Thanks a lot for this plugin, it looks very promising!

I get the error "Duplicate key for property path" when trying to build. I am using the plugin @gridsome/source-filesystem to read the posts for a blog (.md files) and I believe that is where the problem is coming from.

Plugin configuration

// lines with "es" locale commented to try to find the bug, but not working either

plugins: [
    {
      use: "gridsome-plugin-i18n",
      options: {
        locales: [
          // locales list
          "en-us",
          // "es-es",
        ],
        pathAliases: {
          // path segment alias for each locales
          "en-us": "en",
          // "es-es": "es",
        },
        // enablePathRewrite: true,
        fallbackLocale: "en-us", // fallback language
        defaultLocale: "en-us", // default language
        messages: {
          "en-us": require("./src/locales/en-us.json"), // Messages files
          // "es-es": require("./src/locales/es-es.json"),
        },
      },
    },
    {
      use: "@gridsome/source-filesystem",
      options: {
        baseDir: "./blog",
        pathPrefix: "/blog",
        path: "*.md",
        typeName: "BlogPost",
      },
    },
  ],
  templates: {
    BlogPost: "/blog/:id",
  },

Output

$ gridsome build
Gridsome v0.7.14

Initializing plugins...
Load sources - 0.07s
Create GraphQL schema - 0.06s
Error: Duplicate key for property path: /blog/8d665038979865f0a622d11ead24e5f6
    at UniqueIndex.set (/Users/inaki/dev/akademia/web/node_modules/lokijs/src/lokijs.js:7329:17)
    at Collection.add (/Users/inaki/dev/akademia/web/node_modules/lokijs/src/lokijs.js:5974:31)
    at Collection.insertOne (/Users/inaki/dev/akademia/web/node_modules/lokijs/src/lokijs.js:5738:17)
    at Collection.insert (/Users/inaki/dev/akademia/web/node_modules/lokijs/src/lokijs.js:5677:21)
    at Route.addPage (/Users/inaki/dev/akademia/web/node_modules/gridsome/lib/pages/pages.js:473:19)
    at Pages.createPage (/Users/inaki/dev/akademia/web/node_modules/gridsome/lib/pages/pages.js:176:18)
    at createPage (/Users/inaki/dev/akademia/web/node_modules/gridsome/lib/app/actions.js:260:24)
    at VueI18n.createManagedPages (/Users/inaki/dev/akademia/web/node_modules/gridsome-plugin-i18n/gridsome.server.js:63:7)
    at Plugins.run (/Users/inaki/dev/akademia/web/node_modules/gridsome/lib/app/Plugins.js:141:17)
    at process.internalTickCallback (internal/process/next_tick.js:77:7)

How do you navigate to the user's browser language?

Is there any preferred way to do this? I was thinking on using beforeEach but that doesn't sound right as it may override people purposely entering the URL in a different language, I want to navigate by default to the user's language but let him freely change the URL if he wishes

Language switches to default when using templates (pages generated using pageAPI)

Hi @daaru00,

I notice that the plugin doesn't work correctly when I use the pageAPI to create a page. For some reason, the current language changes when I navigate from a page component (automatically generated by Gridsome through the "pages" folder) to template pages (generated via page API using a component in the "templates" folder). When navigating to a template created page, or entering (refresh) a template page, the language always reverts to the default language (based on $i18n.locale).

I reproduced the problem in a new repo for you to have a look. In the example, you'll see that when you navigate between any pages, excluding "contact" and "extra", the plugin works fine. When visiting the "contact" or the "extra" page which are generated using a template, it switches languages automatically to default.

To Reproduce
Steps to reproduce the behaviour:
check out this example repo https://github.com/tandeman77/gridsome-test

Expected behaviour
Expected behaviour should be that language stays the same as the previous page.

Environment (please complete the following information):

  • OS: Windows 10
  • NodeJS Version: v12.16
  • Gridsome Version: 0.7.0
  • Browser: Chrome
  • Plugin Version: "daaru00/gridsome-plugin-i18n#fix/duplicated-path"

Plugin configuration

{
      use: "gridsome-plugin-i18n",
      options: {
        locales: [
          // locales list
          "en-GB",
          "th-TH",
        ],
        pathAliases: {
          // path segment alias for each locales
          "en-GB": "en",
          "th-TH": "th",
        },
        fallbackLocale: "en-GB", // fallback language
        defaultLocale: "en-GB", // default language
        enablePathRewrite: true, // rewrite path with locale prefix, default: true
        rewriteDefaultLanguage: false, // rewrite default locale, default: true
      },
    },  'fr-fr': require('./src/locales/fr-fr.json'),
          'de-de': require('./src/locales/de-de.json'),
          'en-gb': require('./src/locales/en-gb.json'),
        }
      }
    }

Add support for HTML lang attribute

Is your feature request related to a problem? Please describe.
HTML lang attribute does not respect the page language.

Describe the solution you'd like
Change head html attribute as Gridsome guide specify:

export default function (Vue, { head }) {
  // Add attributes to HTML tag
  head.htmlAttrs = { lang: 'en' }
  
  // Add attributes to BODY tag
  head.bodyAttrs = { class: 'custom-body-class' }
}

pathAliases retrieval

Hi! I'm working on a mgi language gridsome website, with netlifycms. The languages are defined with full ISO codes (en-US, ff-FR,...) and they receive an alias for cleaner routes (en, fr,...)

NetlifyCMS is set with locales as en, fr and alike because if I use full ISO codes, GraphQL throw errors (it refuse to accept en-US as a query property). Single-file structure.

Now, I need to populate my pages, and I need to filter content by the current locale, however, if I use i18n.locale, it expect en-US, not en, while netlifycms has languages set as en. I though that I could query by the pathAliases, but I'm not able to retrieve it, only route.path, which has also the following slug.

So, any ideas how can I solve that, without turn to simple, reduced locales definition, as en, fr,...?

How sort languages?

Hi,

In my case, I have this languages locales: ['en', 'es', 'ch', 'gr'], but in LanguageSwitcher languages ​​are sorted alphabetically. Is it possible to make the languages ​​appear in the order that was specified in the config?

With regards.

Warning from vue-router: Duplicate named routes definition for 404 route

Hello!

As I'm now using your plugin in my personal project, I have a question regarding a router-related warning showing up in the console when I'm working with gridsome develop :

image

I think this message is due to the internal workflow of the plugin (creating 2 different 404 routes, one for each of the two languages I have set), have you ever encountered this message? If so, how could we fix the routing and/or the warning about the 404 route?

Thanks in advance! 😄

Cécile

Package Size

We have 23 Languages and 30 Countries, i18n works fine but we have huge problem with the package size of the bundled app.js file, it is over 7mb in size.

Is there any way to exclude the json files from the translation and load it dynamically on the client side?

How to use i18n only at build time, without adding to client JS bundle?

Is your feature request related to a problem? Please describe.
I would like to use i18n at build time for generating HTML, but not at runtime. Currently, it seems that this package adds to app.js. In our case, disabling the i18n plugin reduced app.js from 770kB to 240kB.

Describe the solution you'd like
Either documentation on how to achieve this with the existing configuration options, new options if they're needed to accommodate this.

Describe alternatives you've considered
We could simply disable all JS from being included in our pages by tweaking index.html. But sometimes we do want some client-side JS, just not for i18n purposes.

Cannot read property '$i18n' of undefined

Describe the bug
I am getting an error in the console after installing the plugin, setting up a basic config and copy pasting the language switcher example component. I feel like I am missing some part of the setup process, but I don't know which...

This is my gridsome.config.js plugin config:

{
      use: "gridsome-plugin-i18n",
      options: {
        locales: [
          'nl-nl',
          'en-us'
        ],
        pathAliases: {
          'nl-nl': 'nl',
          'en-us': 'en'
        },
        fallbackLocale: 'nl',
        defaultLocale: 'nl',
        messages: {}
      }
    }

copy pasting the example language switcher on https://gridsome.org/plugins/gridsome-plugin-i18n:

<template>
  <select v-model="currentLocale" @change="localeChanged">
    <option v-for="locale in availableLocales" :key="locale" :value="locale">{{ locale }}</option>
  </select>
</template>

<script lang="js">
export default {
  name: "LocaleSwitcher",
  data: () => {
    return {
      currentLocale: this.$i18n.locale.toString(),
      availableLocales: this.$i18n.availableLocales
    }
  },
  methods: {
    localeChanged () {
      this.$router.push({
        path: this.$tp(this.$route.path, this.currentLocale, true)
      })
    }
  }
}
</script>

I can see, after rebuilding (successfully) that my site now has language prefixes, i.e. /{lang}/blog etc. etc.
However, the $i18n property is not available on the Vue prototype, it seems:

[Vue warn]: Error in data(): "TypeError: Cannot read property '$i18n' of undefined"

found in

---> <LocaleSwitcher> at src/components/LocaleSwitcher.vue
       <Layout> at src/layouts/Default.vue
         <App> at src/App.vue
           <Root>

To Reproduce
Steps to reproduce the behavior:
this is my current package.json (based off of the sanity gridsome starter, updating some dependencies and adding others)

{
  "name": "sanity-gridsome-web",
  "private": true,
  "scripts": {
    "build": "gridsome build",
    "dev": "gridsome develop",
    "explore": "gridsome explore"
  },
  "dependencies": {
    "@sanity/image-url": "^0.140.22",
    "dotenv": "^8.6.0",
    "gridsome": "^0.7.23",
    "gridsome-source-sanity": "^1.0.5",
    "sanity-blocks-vue-component": "^0.1.0"
  },
  "devDependencies": {
    "@tailwindcss/forms": "^0.3.2",
    "gridsome-plugin-bundle-analyzer": "^1.0.0",
    "gridsome-plugin-i18n": "^1.6.0",
    "gridsome-plugin-tailwindcss": "^4.1.1",
    "gridsome-plugin-typescript": "^0.4.0",
    "lodash": "^4.17.21",
    "node-sass": "^4.14.1",
    "sass-loader": "^8.0.2",
    "tailwindcss": "^2.1.2",
    "ts-loader": "^9.1.1",
    "typescript": "^4.2.4"
  }
}

Expected behavior
I expected the $i18n property to be there and moreover, having a simple language switcher to demo the language switching to work.

Screenshots
N/A

Environment (please complete the following information):

  • OS: Mac OSX 11.3.1 (big sur)
  • NodeJS Version: v14.15.1
  • Gridsome Version Version: 0.7.23
  • Browser: Chrome
  • Plugin Version: 1.6.0

Plugin configuration
pasted earlier, above

Translation issues on 404 (not found) route

Describe the bug
When reaching a route which does not exist while using a specific language prefix (example: /en/fake-route) the route will not be displayed in english (URL prefix language) but in default language.

To Reproduce
Steps to reproduce the behavior:

  1. Go to any route that doesn't exist in your Gridsome app, with a language prefix at the beginning of the path
  2. The route should be in the prefix language, it's not, it's in the default language which was configured in gridsome-i18n instead.

In gridsome.client.js, when entering this kind of non-existing route, in beforeEach hook, the value of to.meta.locale is always the default language, the prefix is not taken into account => the route is in default language.

Expected behavior
The 404 route and template is in the language specified as prefix in the URL.

I haven't found a workaround yet, which is a problem because when a user reaches a non-existing page somehow, it will be shown an error page in French instead of its own language (say, English).

with "rewriteDefaultLanguage" the gridsome pages not have locale for page-query

Describe the bug
All default page of gridsome (create by gridsome before the plugin) not receive context locale in route

To Reproduce
Steps to reproduce the behavior:

  1. Go to '/'
  2. the page-query locale variables is empty

Expected behavior

For example in my index page I want make this query

query blogPosts($locale: String) {
  allBlogPost(filter: { lang: { eq: $locale } }) {
    edges {
      node {
        id
        title
      }
    }
  }
}

but with rewriteDefaultLanguage: false for the urls like / $locale is empty
because gridsome create an managed page and it's exclude in plugin

if (options.path !== '/404' && options.internal.isDynamic === false && options.internal.isManaged === false) {

I think I don't really understand why the managed pages are exclude.

Environment (please complete the following information):

  • OS: [e.g. Linux]
  • NodeJS Version [e.g. v12.16.3]
  • Gridsome Version Version [e.g. 0.7.19 ]
  • Browser [e.g. chrome, firefox, safari]
  • Plugin Version [e.g. 1.5.1]

Plugin configuration

{
  use: 'gridsome-plugin-i18n',
  options: {
    locales: [
      'fr',
      'en',
    ],
    fallbackLocale: 'en', // fallback language
    defaultLocale: 'fr', // default language
    rewriteDefaultLanguage: false,
  },
}

Disable/exclude redirect(Rewrite) for assets (Get 404 not found)

Describe the bug
All assets work fine when browsing in the default language. But when we switch to the English language and refresh the page, 404 errors are present for all assets (asset paths are rewritten).

To Reproduce
Steps to reproduce the behavior:

  1. Install plugin
  2. Use somes assets paths in main.js
  3. Run project
  4. Switch to another language
  5. See error in console

Expected behavior
Maintain default links for assets, no rewriting

Screenshots
If applicable, add screenshots to help explain your problem.
Capture d’écran du 2021-08-12 09-22-54

Environment

  • OS: [Ubuntu 20.04]
  • NodeJS Version [v14.17.3]
  • Gridsome Version Version [^0.7.14]
  • Browser [chrome]
  • Plugin Version [^1.6.0]

Plugin configuration

{
      use: "gridsome-plugin-i18n",
      options: {
        locales: [
          // locales list
          "en",
          "fr",
        ],
        fallbackLocale: "fr", // fallback language
        defaultLocale: "fr", // default language
        enablePathRewrite: true, // rewrite path with locale prefix, default: true
        rewriteDefaultLanguage: false, // rewrite default locale, default: true
        enablePathGeneration: false,
        routes: require("../src/routes.js"),
      },
}

Localised routes

Following the instructions at gridsome i18n plugin documentation, I'm currently experiencing a very weird behaviour. I have my i18n plugin configured this way:

module.exports = {
  use: "gridsome-plugin-i18n",
  options: {
    locales: [
      'en-US',
      'it-IT',
      'pt-BR'
    ],
    pathAliases: {
      'en-US': 'en',
      'it-IT': 'it',
      'pt-BR': 'pt'
    },
    fallbackLocale: 'en-US',
    defaultLocale: 'en-US',
    enablePathRewrite: true,
    rewriteDefaultLanguage: true,
    enablePathGeneration: false,
    routes: require('../locales/routes.js')
  }
}

and a routes.js file with the following content:

module.exports = {
  "en-US": [
    {
      path: '/en',
      component: './src/pages/Index.vue'
    },
    {
      path: '/en/about/',
      component: './src/pages/About.vue'
    }
  ],
  "it-IT": [
    {
      path: '/it',
      component: './src/pages/Index.vue'
    },
    {
      path: '/it/about/',
      component: './src/pages/About.vue'
    }
  ],
  "pt-BR": [
    {
      path: '/pt',
      component: './src/pages/Index.vue'
    },
    {
      path: '/pt/about/',
      component: './src/pages/About.vue'
    }
  ]
}

As it is listed, it works perfectly, however the about slug aren't localised; they still are called "about", only their locale code prefix is changed.

If I translate the path strings in routes.js, as demonstrated in the documentation

module.exports = {
  en: [
    {
      path: '/en/',
      component: './src/pages/Index.vue'
    },
    {
      path: '/en/about/',
      component: './src/pages/About.vue'
    }
  ],
  it: [
    {
      path: '/',
      component: './src/pages/Index.vue'
    },
    {
      path: '/it/chi-siamo/',
      component: './src/pages/About.vue'
    }
  ]
};

while having <g-link class="nav__link" :to="$tp('/about')">About</g-link> in my headers, it still expect paths as /en/about, /it/about and so on, so if navigate to /it/about, for example, it thrown an error, as the localised path for the italian language is /it/chi-siamo, not /it/about.


If I follow another logic, so using translated strings and locales, as something like that in my locale JSON:

{
  "code": "it",
  "iso": "IT",
  "welcome": "Benvenuto a Gridsome i18n!",
  "slug": {
    "about": "chi-siamo"
  }  
}

and links as <g-link class="nav__link" :to="$t('code') + '/' + $t('slug.about')">About</g-link> in my header, it works, but if I change the locale while in /it/chi-siamo, for example, it again thrown an error, because it expect to land to a page called /en/chi-siamo, which do not exists.

Of course, I could write alternatives routes for each and every page with a fallback path expected as coming from a language but, as I usually work with website translated in more than five languages, it will became absurd.

It's pretty probable that I missed something from the documentation, however I'm quite lost at the moment. Any clue? Should I give up and remain with unlocalised path? Hope not... ;)

Preferred way to do routing

First of all, very promising plugin, thank you for that. I'm just wondering how your preferred way of doing routing within the same language looks like?

G-links & Locale Switcher fail when you first reach the URL. Reload & all works OK (Netlify Host)

Describe the bug
When you first reach the URL https://stiftungsfonds.netlify.app/ the Locale Switcher doesn't work and all Nav/g-links don't work. If you reload the page, everything works fine. Site is hosted by Netlify.

To Reproduce

  1. Go to https://stiftungsfonds.netlify.app/
  2. Click on Nav links or Hero link - Links are not working
  3. Try Locale Switcher toggle - Locale switcher is not working
  4. Reload page
  5. Click on Nav links or Hero link - Links work
  6. Try Locale Switcher - Locale switcher works

Expected behaviour
G-links & Locale Switcher should function on the first load.

Screenshots
Please see URL or code snippets below.

Environment (please complete the following information):

  • OS: iOS
  • NodeJS: v12.6.0
  • Gridsome: 0.7.13
  • Browser: Chrome, firefox
  • Plugin: 1.6.0
  • Hosting: Netlify

Plugin configuration
gridsome.plugin.js

{
      use: 'gridsome-plugin-i18n',
      options: {
        locales: ['de-DE', 'en-GB'],
        pathAliases: {
          'de-DE': 'de',
          'en-GB': 'en',
        },
        fallbackLocale: 'de-DE', // fallback language
        defaultLocale: 'de-DE', // default language
        enablePathRewrite: true, // rewrite path with locale prefix, default: true
        rewriteDefaultLanguage: true, // rewrite default locale, default: true
        enablePathGeneration: true, // disable path generation
        routes: require('./routes'),
      },
    },

main.js

import DefaultLayout from '~/layouts/Main.vue'

import '~/resources/main.scss'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { config, library } from '@fortawesome/fontawesome-svg-core'
import { faGlobeEurope, faEuroSign } from '@fortawesome/free-solid-svg-icons'
import '@fortawesome/fontawesome-svg-core/styles.css'

config.autoAddCss = false
library.add(faGlobeEurope, faEuroSign)

export default function(Vue, { appOptions }) {
  Vue.component('Layout', DefaultLayout) // Set default layout as a global component
  Vue.component('font-awesome', FontAwesomeIcon)

  appOptions.i18n.setLocaleMessage('de-DE', require('./locales/de-DE.json'))
  appOptions.i18n.setLocaleMessage('en-GB', require('./locales/en-GB.json'))
}

Header.vue

<template>
  <header
    id="header"
    class="px-3 bg-gray-100 flex flex-wrap justify-between items-end py-1 lg:pb-0 border-b border-gray-300"
    role="banner"
  >
    <g-link class="self-start py-6" to="/" aria-label="Back to home">
      <g-image
        class="max-w-xl w-56"
        alt="Stiftungsfonds Zivile Seenotrettung"
        src="~/resources/svg/stiftung_seenotrettung-logo.svg"
        immediate
      />
    </g-link>
    <label for="menu-toggle" class="self-center cursor-pointer lg:hidden block">
      <g-image
        alt="Menu toggle button"
        src="~/resources/svg/menu-outline.svg"
        width="40"
        height="40"
        immediate
      />
    </label>
    <input type="checkbox" class="hidden" id="menu-toggle" />
    <nav
      id="menu"
      class="hidden flex-grow lg:flex lg:justify-end lg:items-center lg:w-auto w-full"
    >
      <ul class="lg:flex items-center justify-between pt-4 lg:pt-0">
        <li>
          <g-link
            :to="$tp('/about/')"
            class="transition-colors ease-in duration-200 my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-900 text-base border-b-2 border-transparent hover:border-indigo-500"
            active-class="is-active-link"
            exact-active-class="border-b-2 border-indigo-500"
            ><span>{{ $t('nav[0].name') }}</span></g-link
          >
        </li>
        <li>
          <g-link
            :to="$tp('/project/')"
            class="transition-colors ease-in duration-200 my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-900 text-base border-b-2 border-transparent hover:border-indigo-500"
            active-class="is-active-link"
            exact-active-class="border-b-2 border-indigo-500"
            ><span>{{ $t('nav[1].name') }}</span></g-link
          >
        </li>
        <li>
          <g-link
            :to="$tp('/apply/')"
            class="transition-colors ease-in duration-200 my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-900 text-base border-b-2 border-transparent hover:border-indigo-500"
            active-class="is-active-link"
            exact-active-class="border-b-2 border-indigo-500"
            ><span>{{ $t('nav[2].name') }}</span></g-link
          >
        </li>
        <li>
          <g-link
            :to="$tp('/press/')"
            class="transition-colors ease-in duration-200 my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-900 text-base border-b-2 border-transparent hover:border-indigo-500"
            active-class="is-active-link"
            exact-active-class="border-b-2 border-indigo-500"
            ><span>{{ $t('nav[3].name') }}</span></g-link
          >
        </li>
        <li>
          <g-link
            :to="$tp('/donate/')"
            class="transition-colors ease-in duration-200 my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-900 text-base border-b-2 border-transparent hover:border-indigo-500"
            active-class="is-active-link"
            exact-active-class="border-b-2 border-indigo-500"
            ><span>{{ $t('nav[4].name') }}</span></g-link
          >
        </li>
        <li>
          <g-link
            :to="$tp('/imprint/')"
            class="transition-colors ease-in duration-200 my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-900 text-base border-b-2 border-transparent hover:border-indigo-500"
            active-class="is-active-link"
            exact-active-class="border-b-2 border-indigo-500"
            ><span>{{ $t('nav[5].name') }}</span></g-link
          >
        </li>
        <!-- <li v-for="item in $t('nav')" :key="item.name"> // BUG: this breaks active classes
          <g-link
            :to="$tp(item.link)"
            class="transition-colors ease-in duration-200 my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-700 text-lg border-b-1 border-transparent hover:border-indigo-500"
            active-class="is-active-link"
            exact-active-class="text-gray-700 border-b-1 border-indigo-500"
            >{{ item.name }}</g-link
          >
        </li> -->
        <li>
          <LocaleSwitcher
            class="my-1 lg:mb-4 mx-2 tracking-loose inline-block text-gray-900 text-lg border rounded"
          />
        </li>
      </ul>
    </nav>
  </header>
</template>

<script>
import LocaleSwitcher from '~/components/LocaleSwitcher.vue'
export default {
  components: {
    LocaleSwitcher,
  },
}
</script>

<static-query>
query {
  metadata {
    siteName
    menu {
      name
      link
    }
  }
}
</static-query>

About Me & the Project
Hi, I'm Mel Jones, I'm a self-taught dev and new to Gridsome & Vue. I'm building this site for an NGO called SeaWatch any help you can give, would be very much appreciated!

Cheers,
Mel

Localized routes

Is your feature request related to a problem? Please describe.
It would be nice to have the possibility to customize the name of the routes for each single supported locale.

Describe the solution you'd like
With the page "/projects" and the locales "en" and "it", it would be nice to have:
"/en/projects" localized to "/it/progetti".

Describe alternatives you've considered
Solutions like the one provided by Vue Router would be a nice to have:
https://router.vuejs.org/guide/essentials/nested-routes.html

Proposal of plugin's configuration changes

{
      use: "gridsome-plugin-i18n",
      options: {
        routes: [
          { 
             path: '/it',
             component: './src/layouts/Default.vue'
             children: [
               { path: 'progetti', component: './src/pages/Projects.vue' }
               { path: 'contatti', component: './src/pages/Contacts.vue' }
             ]
          },
          { 
             path: '/en', 
             component: './src/layouts/Default.vue'
             children: [
               { path: 'projects', component: './src/pages/Projects.vue' }
               { path: 'contacts', component: './src/pages/Contacts.vue' }
             ]
          },
        ]
      }
    }

Add a feature to $tp, so default language is not prefixed

Thank you for your working. This package helps a lot! I would love to add one feature to $tp.

With my current settings I generate the links like this:

/                    -> component home
/it-it/              -> component home
/en-gb/              -> component home
/en-gb/about         -> component about
/it-it/about         -> component about
/about               -> component about
/it-it/about         -> component about

For each link without prefix, the default language is being used. So now using $tp it forces me to en-gb. And I don't want to add a prefix only if it's a foreign language (looked at the domain ending).

For more e.g. #2 (comment)

I hope it's understandable

$i18n.locale behaving differently in templates vs pages

Using {{$i18n.locale}} in a page file gives the correct locale. However, using {{$i18n.locale}} in a template file always returns the default locale.

I am using Contentful (@gridsome/source-contentful) to generate template pages with localized data.

Expected behavior
I would expect {{$i18n.locale}} to behave the same in all gridsome file types (layouts, templates, pages).

Environment:

  • Gridsome Version 0.7.0
    -gridsome-plugin-i18n version 1.6.0

gridsome.config.js

module.exports = {
  siteName: "siteName",
  templates: {
    ContentfulContentPage: [{
      path: (node) =>  `/${node.locale === 'en-US' ? 'en' : 'cn'}/${node.slug}`
    }],
  },
  plugins: [
    {
      use: "@gridsome/source-contentful",
      options: {
        space: {{space}}, // required
        accessToken: {{accessToken}}, // required
        typeName: "Contentful",
        locales: ["en-US", "zh-CN"],
      },
    },
    {
      use: "gridsome-plugin-i18n",
      options: {
        locales: [
          // locales list
          "en-US",
          "zh-CN",
        ],
        pathAliases: {
          // path segment alias for each locales
          "en-US": "en",
          "zh-CN": "cn",
        },
        fallbackLocale: "en-US", // fallback language
        defaultLocale: "en-US", // default language
        enablePathRewrite: false, // rewrite path with locale prefix, default: true
        rewriteDefaultLanguage: true, // rewrite default locale, default: true
      },
    },
    {
      use: "@noxify/gridsome-plugin-remote-image",
      options: {
        cache: false,
        typeName: "ContentfulAsset",
        sourceField: "file.url",
        targetField: "localFile",
        targetPath: "src/assets/cf/remoteImage",
      },
    },
  ],
};

Language prefix in path breaks active class on g-link

Describe the bug
I have an app with two routes / and /about/ and two locales 'en' (default) and 'hi'.
I am rewriting paths using the enablePathRewrite flag set to true and rewriteDefaultLanguage set to false.
This yields the following 6 paths:

  1. /
  2. /about/
  3. /en/
  4. /en/about/
  5. /hi/
  6. /hi/about/

The active class on the g-links (which have their to prop set to '/' and '/about/') only works on the unprefixed versions (0 and 1). In all other paths, the g-links are inactive.

To Reproduce
Steps to reproduce the behavior:

  1. Setup 2+ routes and 2+ locales.
  2. Set enablePathRewrite to true and rewriteDefaultLanguage to false
  3. Visit unprefixed routes, g-links are active as expected
  4. Visit prefixed routes, g-links are inactive

Expected behavior
g-links should also be active on locale-prefixed URLs.

Environment (please complete the following information):

  • OS: [e.g. macOS]
  • NodeJS Version [e.g. v12.16.1]
  • Gridsome Version Version [e.g. 0.7.0 ]
  • Browser [e.g. Firefox]
  • Plugin Version [e.g. 1.5.1]

Plugin configuration

{
  use: "gridsome-plugin-i18n",
    options: {
      locales: [
        'en', // English
        'hi' // Hindi
      ],
      fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
      defaultLocale: process.env.VUE_APP_I18N_DEFAULT_LOCALE || 'en',
      silentFallbackWarn: true, // we actually use fallback translations
      rewriteDefaultLanguage: false,
      messages: {
        en: require('./src/locales/en.json'),
        pr: require('./src/locales/hi.json')
      }
    ]
  }
}

Something I tried
If I change the to prop on the g-links to $tp('to') and $tp('/about/') respectively, the active status works for routes 0, 1, 4 and 5 (but not 2 and 3, which I think is because of rewriteDefaultLanguage set to false). Is there a way to redirect 2 and 3 to 0 and 1 respectively when rewriteDefaultLanguage is set to false?

child "path" fails because ["path" with value "\de-de\404\" fails to match the leading slash pattern

Hi @daaru00,

I´ve already mentioned it in #1 but I thought I´d create a separate issue to make it easier to find for others.

I´m running into the following issue:

Create GraphQL schema - 0.1s
Error: child "path" fails because ["path" with value "\de-de\404\" fails to match the leading slash pattern]
    at validate (C:\Users\MyPC\IdeaProjects\gridsome-i18n\node_modules\gridsome\lib\pages\schemas.js:54:11)
    at Pages.createPage (C:\Users\MyPC\IdeaProjects\gridsome-i18n\node_modules\gridsome\lib\pages\pages.js:165:21)
    at createPage (C:\Users\MyPC\IdeaProjects\gridsome-i18n\node_modules\gridsome\lib\app\actions.js:260:24)
    at VueI18n.createManagedPages (C:\Users\MyPC\IdeaProjects\gridsome-i18n\node_modules\gridsome-plugin-i18n\gridsome.server.js:47:9)
    at Plugins.run (C:\Users\MyPC\IdeaProjects\gridsome-i18n\node_modules\gridsome\lib\app\Plugins.js:141:17)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Plugins.createPages (C:\Users\MyPC\IdeaProjects\gridsome-i18n\node_modules\gridsome\lib\app\Plugins.js:116:5)
with this configuration
{
           use: "gridsome-plugin-i18n",
           options: {
               locales: [ 
                   'de-de',
                   'en-us'
               ],
               pathAliases: {
                   'de': 'de',
                   'en': 'en'
               },
               fallbackLocale: 'en-us',
               defaultLocale: 'en-us', 
               messages: {
                   'de-de': require('./src/locales/de-de.json'),
                   'en-gb': require('./src/locales/en-us.json'),
               }
           }
       },

Can you reproduce that on your side?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.