∺ Hingejs

i18n - internationalization

If your site needs to be translated into various language's, there is a setup with the use of i18next.com.

↩ Go Back

Sample code

    <h1 data-i18n="global:header"></h1>
    <button class="en">English</button>
    <button class="es-pr">Spanish</button>
    <button class="es">Bad Change</button>
    <a href="?locale=en">English Link</a>
    <a href="?locale=es-pr">Spanish Link</a>
    <script type="module">
      import { I18n } from 'https://cdn.jsdelivr.net/npm/@hingejs/services/index.min.js'
      I18n.enableDocumentObserver()

      document.querySelector('button.en').addEventListener('click', () => {
        I18n.setLocale('en')
      })

      document.querySelector('button.es-pr').addEventListener('click', () => {
        I18n.setLocale('es-pr')
      })

      document.querySelector('button.es').addEventListener('click', () => {
        I18n.setLocale('es')
      })
    </script>

  

Working sample

English Link Spanish Link

Adding internationalization to a current project

If you are in a current project and now need to add internationalization please follow the steps below

  1. Add a directory called locales to the assets folder: /assets/locales
  2. Create a file called en.json and add some JSON key/values to start.
            {
              "global:header": "This is the home page"
            }
          
  3. Add the following to the /src/main.js file
              import { I18n } from '@hingejs/services'
              I18n.enableDocumentObserver()
          
  4. Now adding the attribute data-i18n to html tags will allow the key to be translated
              <h1 data-i18n="global:header"></h1>
          
  5. Alternatively you can also use Javascript to translate keys
              const translate = await I18n.init()
              let result = translate('global:header')
          
  6. A custom element can also be created and used. Note this is not included with the hingeJS web components package
            // file: components/translate-locale.js
             import { I18n } from '@hingejs/services'
    
             window.customElements.define('translate-locale', class extends HTMLElement {
    
               constructor() {
                 super()
               }
    
               async generateTemplate() {
                 const translate = await I18n.init()
                 return translate(this.innerText)
               }
    
               async connectedCallback() {
                 this.innerHTML = await this.generateTemplate()
               }
    
             })
          
    in the HTML
              <translate-locale>global:header</translate-locale>