0% encontró este documento útil (0 votos)
4 vistas3 páginas

Soporte multilingüe con LanguageJS

Este documento describe cómo usar una biblioteca JavaScript para traducir elementos HTML a diferentes idiomas. La biblioteca permite crear archivos de traducción en diferentes idiomas y asignar identificadores a los elementos que se van a traducir para reemplazar su texto por las traducciones correspondientes al idioma seleccionado.

Cargado por

Petro Paulo
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
4 vistas3 páginas

Soporte multilingüe con LanguageJS

Este documento describe cómo usar una biblioteca JavaScript para traducir elementos HTML a diferentes idiomas. La biblioteca permite crear archivos de traducción en diferentes idiomas y asignar identificadores a los elementos que se van a traducir para reemplazar su texto por las traducciones correspondientes al idioma seleccionado.

Cargado por

Petro Paulo
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd

LanguageJS/README.

md

language-js
Suporte multi-idioma simple con JavaScript.

Como usarlo:

 Añadir el archivo JavaScript [Link]:

<script src="[Link]"></script>

Y tambien indicar que elementos tienen traduccion (ver Crear las


traducciones en este documento para saber mas):

var LanguageJS = new LanguageJS([


"title",
"description"
]);

 Crear archivos de traduccion. Crea una carpeta llamada /locale/.

Crear los archivos dentro de esa carpeta, el nombre de estos archivos debe ser:

[Link].

identificadorSeccion: Un simple identificador para separar los archivos de


traducción segun la seccion que traduzcan.

identificadorIdioma: Identificador de idioma (Recomendado el standard ISO 639-


1).

Ejemplos:

Seccion Español (es) Ingles (e

[Link] [Link] [Link]


Seccion Español (es) Ingles (e

[Link] [Link] [Link]

 Crear las traducciones:

Dentro de cada archivo antes creado, se deben crear las traducciones con esta
estructura:

var localization = {
identificador: "Texto de traudccion",
};

Por ejemplo:

var localization = {
titulo: "Mi pagina",
descripcion: "Esta es mi pagina web."
};

 Asignar identificadores a cada elemento HTML a traducir:

Para que se traduzca correctamente, debemos ir a nuestra HTML y añadir una


clase que relacione el objeto con el texto que nemos introducido en los archivo
de traduccion. Para que no existan confusiones sobre las clases, estas lleva un
prefijo (lang__) del que va acompañado el identificador:

<p class="lang__identificador">Texto</p>

Ejemplo:

<p class="lang__titulo">Mi pagina</p>

 Llamar a la funcion para traducir: Funcion en JavaScript:

[Link]('identificadorIdioma', 'identificadorSeccion');

Por ejemplo:

[Link]('es', 'index');

Este seria un ejemplo con varios idiomas:

<a href="#" onclick="[Link]('es', 'index');">Español</a>


<a href="#" onclick="[Link]('en', 'index');">Ingles</a>
<a href="#" onclick="[Link]('it', 'index');">Italiano</a>
[Link]

function LanguageJS(itemsToTranslate) {

[Link] = function(){
var languageFile = [Link]('languageFile');
(languageFile != null) ?
[Link](languageFile):"";
languageFile = [Link]('script');
[Link] = "locale/bd-" + [Link] + "-" +
[Link] + ".js";
[Link] = "languageFile";
[Link]('body')[0].appendChild(languageFile);
}

[Link] = function(languageID, sectionID) {


[Link] = new String(languageID);
[Link] = new String(sectionID);
[Link]();
var languageFile = [Link]('languageFile');
[Link] = function(){
for (var i in itemsToTranslate) {
var elementToTranslate =
[Link]('lang__' + itemsToTranslate[i]);
for (var o in elementToTranslate) {
elementToTranslate[o].innerHTML =
localization[itemsToTranslate[i]];
}
}
}
}
}

Common questions

Con tecnología de IA

The 'translate' function in LanguageJS is responsible for changing the displayed language on a webpage. It operates by accepting 'languageID' and 'sectionID' as parameters, updating the properties of the LanguageJS instance, dynamically loading the corresponding translation file, and updating all HTML elements identified to be translated. It assigns content from the loaded localization object to the innerHTML of elements with matching 'lang__' class names .

Translation files in LanguageJS are organized within a directory named '/locale/' and are named using the pattern 'bd-seccionID-idiomaID.js'. The 'seccionID' serves to differentiate the files based on the section of the application they translate, while the 'idiomaID' uses ISO 639-1 language codes to specify the language, thus describing both the content and the language of the translation file .

The ISO 639-1 standard is recommended for language identifiers in LanguageJS to ensure consistency and universality in identifying languages across different projects. By adhering to this widely recognized two-letter code standard, developers can easily integrate with other systems and avoid confusion or conflicts, hence improving code maintainability and system efficiency .

The 'lang__' prefix in class names is used to create a clear and specific association between the HTML elements and their corresponding translation entries in the localization files. This prefix helps avoid class name collisions and ensures that the correct text substitution occurs for each element by identifying which portion of text needs to be translated .

Once a translation file is loaded, LanguageJS updates the content of HTML elements by iterating over an array of item identifiers initially specified during its instantiation. For each item, it gathers all HTML elements that have class names prefixed with 'lang__' followed by the item identifier. It then replaces the innerHTML of these elements with the localized text corresponding to each item identifier in the loaded translation file .

To implement multilingual support with LanguageJS, follow these steps: add the language.js script to the HTML document, specify the elements that require translation using the LanguageJS constructor, create translation files structured as 'bd-seccionID-idiomaID.js' within a '/locale/' directory, prepare the translation entries in these files with unique identifiers, assign identifiers via the 'lang__' class prefix in the HTML, and call the 'LanguageJS.translate' function with appropriate language and section identifiers to trigger the language switch .

Section identifiers in LanguageJS are significant for categorizing translation files according to different application sections, thereby allowing targeted loading of necessary translations without overloading the client-side with unnecessary data. They ensure that only relevant translations are used when a user navigates through different sections of a website, facilitating better organization and performance optimization .

LanguageJS ensures that the correct translations are displayed by leveraging structured class naming conventions ('lang__identifier') that map precisely to entries in the language files. When a language change is initiated, it remaps these elements to the up-to-date localization data from the dynamically loaded language file, ensuring each element's text content matches the current language setting accurately .

LanguageJS handles dynamic loading of translation files by first checking if a translation script element with the ID 'languageFile' exists on the page. If it does, the function removes it. Then, it creates a new script element, constructs its source path using the format 'locale/bd-seccionID-idiomaID.js', and appends it to the 'body' of the document. Once this script is successfully loaded, it translates the HTML elements by replacing their inner content with the appropriate text from the newly added localization object .

The 'LanguageJS.translate' function manages multiple language translations dynamically by taking 'languageID' and 'sectionID' as parameters to identify which translation file to load. It dynamically retrieves and loads the necessary language file, replaces the current HTML content with the localized text by associating class names with translation entries, and updates the content asynchronously, thereby allowing seamless language changes without requiring page reloads .

También podría gustarte