• Stars
    star
    259
  • Rank 157,669 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🎭 Laravel Translator class in JavaScript!

Lang.js – Localization library written in JavaScript highly inspired on Laravel's Lang.

Build Status Laravel 5.5 Laravel 5.0 NPM Montly Downloads GitHub license




Installation

Different installation methods:




Are you interested in the next version?




Documentation

Initialization

var lang = new Lang({
    messages: source,
    locale: 'fr',
    fallback: 'zn'
});

To use Lang.js we need to specify at least the messages sources. This can be done during instantiation as shown in the previous code or later using the setMessages() method.

Messages source format

The messages source format looks like:

{
    "locale1.name": {
        "key1": "value1",
        "key2": "value2",
        // ... and more key-value pairs.
    },
    "locale2.name": {
        "key1": "value1",
        "key2": "value2",
        // ... and more key-value pairs.
    },
    // ... and more locales.
}

See the sample used in tests located at: test/fixture/messages.json.

Methods

setMessages

Set messages source. Check messages source format.

var lang = new Lang();
lang.setMessages(source);

getLocale

Get the current locale, if none set, the default locale will be returned (en).

var lang = new Lang();

lang.getLocale();
// > "en"

lang.setLocale('fr');
lang.getLocale();
// > "fr"

setLocale

Set the current locale.

var lang = new Lang();

lang.setLocale('ht');
lang.getLocale();
// > "ht"

getFallback

Get the fallback locale.

var lang = new Lang();

lang.getFallback();
// > undefined

lang.setFallback('de');
lang.getFallback();
// > "de"

setFallback

Set the fallback locale. When retrieving a message (using get() or has()) which is not defined in the specified locale, then it will try to find a message with the fallback locale (if set).

var lang = new Lang({
    messages: {
        'en.greetings': {
            'hi': 'Hi',
            'hello': 'Hello'
        },
        'it.greetings': {
            'hi': 'Salve'
        }
    }
});

lang.setLocale('it');
lang.get('greetings.hello');
// > "greetings.hello"

lang.setFallback('en');
lang.get('greetings.hello');
// > "Hello"

has

Indicate if a given key is defined on the messages source. Return true if the key is defined on the messages source, otherwise false. This method will try to get a message for the specified locale, if not found, then it will return a message for the fallback locale, if not found, then false will be returned.

var lang = new Lang({
    messages: {
        'en.greetings': {
            'hi': 'Hi'
        },
        'es.greetings': {
            'hi': 'Hola'
        }
    }
});

lang.has('greetings.hi');
// > true

lang.has('greetings.hi', 'es');
// > true

lang.has('greetings.hello');
// > false

get

Get a translation message if found, otherwise return the given key. This method will try to get a message for the specified locale, if not found, then it will return a message for the fallback locale, if not found, then the given key will be returned.

var lang = new Lang({
    messages: {
        'en.greetings': {
            'hi': 'Hi'
        },
        'es.greetings': {
            'hi': 'Hola'
        }
    }
});

lang.get('greetings.hi');
// > "Hi"

lang.get('greetings.hi', {}, 'es');
// > "Hola"

lang.get('greetings.hello');
// > "greetings.hello"

Get a translation file from a nested directory

Lang.get('forum/thread.hello');
// > "Hello"

Lang.get('forum/thread.hello', {}, 'es');
// > "Hola"

trans

This method act as an alias of get().

choice

Get the plural or singular form of the message specified based on an integer value.

var lang = new Lang({
    messages: {
        'en.fruits': {
            'apple': 'apple|apples'
        },
        'es.fruits': {
            'apple': 'manzana|manzanas'
        }
    }
});

lang.choice('fruits.apple', 1);
// > "apple"

lang.choice('fruits.apple', 4);
// > "apples"

lang.choice('fruits.apple', 4, {}, 'es');
// > "manzanas"

You may even create more complex pluralization rules which specify translation strings for multiple number ranges:

var lang = new Lang({
    messages: {
        'en.fruits': {
            'apple': '{0} There are none|[1,19] There are some|[20,*] There are many'
        }
    }
});

lang.choice('fruits.apple', 0);   
// > "There are none"

lang.choice('fruits.apple', 1);   
// > "There are some"

lang.choice('fruits.apple', 3);   
// > "There are some"

lang.choice('fruits.apple', 20);   
// > "There are many"

lang.choice('fruits.apple', 22);   
// > "There are many

transChoice

This method act as an alias of choice().




Development

  1. Fork this repository and clone it.
  2. Create a branch from develop: git checkout -b feature/xxxxxxx
  3. Submit a PR to be merge into develop branch.

Get help!




Testing

To run the tests use the following commands:

  • Single run: npm run test
  • Run on changes: npm run test:watch

More Repositories

1

Laravel-JS-Localization

🌐 Convert your Laravel messages and consume them in the front-end!
PHP
594
star
2

react-new-window

🔲 Pop new windows in React, using `window.open`.
JavaScript
407
star
3

checkboxes.js

☑️ A jQuery plugin that gives you nice powers over your checkboxes.
JavaScript
130
star
4

laravel-localization-loader

Laravel Localization loader for webpack. Convert Laravel Translation strings to JavaScript Objects.
JavaScript
68
star
5

dom-navigator

⚓️ JS library that allow keyboard navigation through DOM elements (←↑→↓).
JavaScript
40
star
6

react-chronos

⛓ React chronology component providing dual chronological timelines.
JavaScript
39
star
7

github-banner

⚡️ Generate a GitHub banner for your repo!
JavaScript
35
star
8

cloud9-emmet-ext

A Cloud9IDE extension for emmet.io (aka ZenCoding) integration.
JavaScript
26
star
9

lowdb-api

⚡️ lowdb-api - Express middleware that serve a virtual RESTful API.
JavaScript
25
star
10

spotlight-never-index

Exclude some folders from Spotlight.app
JavaScript
21
star
11

Laravel-Translator

Laravel command that interactively helps you translate missing keys.
PHP
19
star
12

config-webpack-plugin

💫 Merge one or more configuration files together with environment variables too.
JavaScript
18
star
13

react-input-handler

⚡️ Utility function to handle input changes in React.
JavaScript
15
star
14

ruty

📦 Ruty is a simple URL route builder, that support typing route params and queries string with TypeScript.
TypeScript
15
star
15

shorted-theme

Shorted theme references for Styled Components.
TypeScript
14
star
16

php-array-to-json

✨ Convert PHP configuration array files to JSON files. Useful to convert Laravel's PHP localization files into JSON files.
JavaScript
10
star
17

mkdir-date

A tool to create directories for each days in a period of time.
JavaScript
10
star
18

jQuery-Ajax-Latency-Simulator-Plugin

A jQuery plugin that simulate latency for any AJAX request via jQuery plugin
JavaScript
9
star
19

grunt-fb-flo

Starts a fb-flo server
JavaScript
8
star
20

Rachel

🚀 Quickly create a RESTful client!
JavaScript
7
star
21

rmariuzzo

Rubens' professional information that appears in GitHub.
JavaScript
6
star
22

fuf-cli

🔍 fuf – Find Unused Files in a directory with a single command.
JavaScript
6
star
23

react-scrollie

Scroll listener React component that provide scrolling info
JavaScript
6
star
24

fotch

Fotch – In browser fake REST API for creative development purposes!
TypeScript
5
star
25

react-grille

Make a grille pattern! AKA grid pattern or mesh!
JavaScript
5
star
26

markdown-exec

Execute commands in your Markdown and keep the output.
JavaScript
5
star
27

fuf

🔍 fuf – Find Unused Files in a directory.
JavaScript
5
star
28

chalk-printer

NodeJS library to print colored message in the console.
JavaScript
5
star
29

inspirabbble

Inspire yourself with fresh shots from Dribbble!
JavaScript
4
star
30

php-array-loader

PHP array loader module for webpack
JavaScript
4
star
31

php-array-parser

✨ Parse a PHP array
JavaScript
4
star
32

Mariuzzo.Web.Mvc.Extras

Extra missing components for ASP.NET MVC.
C#
4
star
33

entrify

📦 Library to convert package.json to index.js.
JavaScript
3
star
34

google-images-url

🔗 URL generator for Google Images
JavaScript
3
star
35

node-typescript-template

A template repo for Node and Typescript.
TypeScript
3
star
36

untoken

A token replacement tool.
TypeScript
3
star
37

calendar

A calendar widget.
TypeScript
3
star
38

untoken-cli

A token replacement CLI tool for text.
TypeScript
3
star
39

Gistie

Gist plugin for October CMS. Provides a simple way to share snippets and pastes with others using Github's gist.
PHP
3
star
40

easy-peasy-thunk-stages

Thunk stages in your model is easy-peasy!
TypeScript
2
star
41

knowledge

List of stuff I have learnt ...
2
star
42

xml-comment-api

Parse XML comment that provide an API
JavaScript
2
star
43

jQuery-Annotation-Plugin

jQuery Annotation Plugin
JavaScript
2
star
44

fixture-middleware

Use fixture data in your express app!
JavaScript
2
star
45

mishell

Mishell: collection of shell utilities.
TypeScript
2
star
46

directory-tree

Generate a tree of directories.
TypeScript
2
star
47

githood

Run commands in a group of git repos.
TypeScript
2
star
48

re-ducks

Library to reduce common tasks for React apps based on re-ducks (https://github.com/alexnm/re-ducks)
JavaScript
2
star
49

restful-api-course

The RESTful API course
JavaScript
2
star
50

attention-jquery-plugin

A jQuery plugin to call attention to any HTML element.
1
star
51

JavaScript-Prototype-Programming-Talk

Code used for the talk "JavaScript Prototype Programming" by @rmariuzzo
JavaScript
1
star
52

jQuery-Lockable-Plugin

A jQuery plugin that locks / unlocks any Textbox.
1
star
53

commons-css

A set of commons CSS to be reused, instead of writing it over & over.
1
star
54

grunt-talk

Introductory talk about Grunt (in spanish) — Automatizando el desarrollo front-end con Grunt.
1
star
55

entrify-cli

📦 CLI tool to convert package.json to index.js.
JavaScript
1
star
56

chronometer

Experiment: Chronometer desktop app using Go and Fyne.
Go
1
star