Automatic translator

0

I have the following problem.

link

I'm using that example to set up my translator.

but he does not do anything to me, I do not know what he's doing wrong.

In the webroot is the home-in and the home-is

home-en.json

{
    "titulo": "Laboratorio estrategico"
}

home-en.json (sorry if it's badly translated, I did it in memory)

{
    "titulo": "Estrategic laboratory"
}

jqueryTranlator.js this was downloaded

 /*
        Name: jqueryTranslator
        Author: Antonio Laguna
        Twitter: @Belelros
        Website: http://www.funcion13.com
        Version: 1.1.1
    */
    (function($, window, document, undefined){
      var Translate = {
        initialize : function(pkg, options){
          this.packages = [];
          this.loaded = $.Deferred();

          this.translatable = true;

          this.options = $.extend({}, $.fn.jqTranslate.options, options);
          var userLanguage = this.getUserLanguage();

          if (typeof pkg === 'string'){
            this.packages.push(pkg);
          }
          else {
            this.packages = pkg;
          }

          if (this.isTranslatable(userLanguage)){
            this.loadLanguages();
          }
          else{
            this.translatable = false;
          }

          return this.loaded.promise();
        },
        getUserLanguage : function(){
          var userLang = this.options.forceLang || navigator.language || navigator.userLanguage;
          $.defaultLanguage = userLang;

          userLang = userLang.replace(/_/, '-').toLowerCase();

          if (userLang.length > 3){
            userLang = userLang.substring(0,3) + userLang.substring(3).toUpperCase();
            this.languages = [
              userLang.substring(0,2),
              userLang.substring(3).toUpperCase()
            ];
          }
          else {
            this.languages = [
              userLang
            ];
          }

          $.fn.jqTranslate.userLang = userLang;
          return userLang;
        },
        isTranslatable : function(language){
          if (this.options.defaultLang === language) { return false; }
          else { return ($.inArray(language, this.options.skip) === -1); }
        },
        loadLanguages : function(){
          var loaded = 0, maxLoad = Translate.languages.length * Translate.packages.length;
          this.translatedStrings = {};

          $.each(Translate.packages,function(i, pkg){
            var ePkg = pkg;

            $.each(Translate.languages, function (i, lang){
              Translate.getLanguage(ePkg,lang)
              .done(Translate.storeLangFile)
              .always(function(){
                loaded++;
                if (loaded >= maxLoad){Translate.loaded.resolve();}
              });
            });
          });
        },
        getLanguage : function(pkg, language){
          var self = this,
              path = '',
              got = $.Deferred();

          if (self.options.path){
            path = self.options.path + '/';
          }
          var url = path + [pkg, language].join('-') + '.json';

          $.ajax ({
            url : url,
            dataType : "json",
            cache : self.options.cache,
            async: self.options.asyncLangLoad
          }).done(function(data){
            got.resolve(data);
          }).fail(function(){
            if (self.options.fallbackLang){
              url = path + [pkg, self.options.fallbackLang].join('-') + '.json';
              $.ajax ({
                url : url,
                dataType : "json",
                cache : self.options.cache,
                async: self.options.asyncLangLoad
              }).done(function(data){
                got.resolve(data);
              });
            }
            else {
              got.reject();
            }
          });

          return got;
        },
        storeLangFile : function(data){
          $.extend(Translate.translatedStrings, data);
        },
        translate : function() {
          var elem = $(this),
              key = elem.data('translate');

          if (Translate.translatable){
            if (Translate.translatedStrings[key]){
              if (Translate.translatedStrings[key].length === undefined){
                // The key have nested keys
                Translate.translateElement(elem,Translate.translatedStrings[key].text);
                delete Translate.translatedStrings[key].text;
                elem.attr(Translate.translatedStrings[key]);
              }
              else{
                Translate.translateElement(elem,Translate.translatedStrings[key]);
              }
            }
          }

          if (typeof Translate.options.onComplete === 'function'){
            Translate.options.onComplete.apply(this, arguments);
          }

          return elem;
        },
        translateElement : function (elem, value){
          if (elem.is('input') || elem.is('textarea')) {
            if (elem.is('[placeholder]')){
              elem.attr('placeholder', value);
            }
            else{
              elem.val(value);
            }
          }
          else if (elem.is('optgroup')){
            elem.attr('label', value);
          }
          else if (elem.is('img')) {
            elem.attr('alt',value);
          }
          else {
            elem.html(value);
          }
        }
      };

      $.fn.jqTranslate = function(pkg, options){
        var self = this;
        Translate.initialize(pkg, options).done(function(){
            self.each(Translate.translate);
        });
        return this;
      };
      $.fn.jqTranslate.options = {
        asyncLangLoad : true,
        cache : true,
        defaultLang : null,
        fallbackLang : null,
        forceLang : null,
        onComplete : null,
        path : null,
        skip : []
      };
    })(jQuery, window, document);

home.ctp It is supposed that he should create the text that I put in the json, but he does not

<h1 class="traducir" data-translate="titulo">

</h1>

<div class="row">
    <div class="col-md-6">

        <div class="row">
            <div class="col-md-8">.col-md-8</div>
            <div class="col-md-4">.col-md-4</div>
        </div>
    </div>
    <div class="col-md-6">ddd</div>
</div>

<script type="text/javascript">
    (function (){
        $("[data-translate]").jqTranslate("home" , {defaultLang: 'es'})
    })();
</script>
    
asked by Andrés Vélez 03.04.2018 в 23:17
source

1 answer

1

This is in the ready of a js and with that I get the default browser language, if you do not recognize it by default it puts it in Spanish

$ (function () {         $ ('. selectpicker'). selectpicker ();     });

var ln = x = window.navigator.language || navigator.browserLanguage;
if (ln.indexOf("en") == 0) {
    $('.selectpicker').val("English");
    lang = "en";
} else if (ln.indexOf("es") == 0) {
    $('.selectpicker').val("Español");
    lang = "es";
} else {
    $('.selectpicker').val("Español");
    lang = "es";
}

$.traducir();

This is the translate function, I go through all the attributes with the lang class, that's very important if the tag does not have that class does not translate it, and then I change the text to each one, looking for the array arrLang which in the first position is the language (in or is) and in the second position is the translation depending on the key field of each label.

$.traducir = function () {
        $('.lang').each(function (index, element) {
            $(this).text(arrLang[lang][$(this).attr('key')]);
            $(this).val(arrLang[lang][$(this).attr('key')]);
            $(this).html(arrLang[lang][$(this).attr('key')]);
        });
    }

Each tag you want to translate must have the key attribute

<h1 id="h1IndexTitulo" class="lang" key="h1IndexTitulo">Laboratorio estrategico</h1>

Create a select to choose languages

<select class="selectpicker" data-width="fit">
                <option  data-content='<span class="flag-icon flag-icon-mx" value="es"></span> Español'>Español</option>
                <option data-content='<span class="flag-icon flag-icon-us" value="en"></span> English'>English</option>
</select>

With this js it is known which language is chosen and changes it

$('.selectpicker').on('change', function () {
    lang="es";
    var ln= $('.selectpicker').val();
    if(ln=="English"){
        lang="en";
    }else if(ln=="Español"){
        lang="es";
    } else {
        lang="es";
    }
    $.traducir();
});

And last but very important, an array with the translations

'en o' es' is always in the lang variable that I always modify before calling the translate function.

var arrLang = {
    'en': {
        'h1IndexTitulo': 'Estrategic laboratory',
        'btn': 'buton'
    },
    'es': {
        'h1IndexTitulo': 'Laboratorio estrategico',
        'btn': 'boton'
    }
};
    
answered by 06.04.2018 в 16:06