• Stars
    star
    143
  • Rank 247,708 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 10 years ago
  • Updated 10 months ago

Reviews

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

Repository Details

Simple, ease-to-use and flexible package for the Laravel web framework. Allows you to use localized messages of the Laravel webapp (see `resources/lang` directory) in your Javascript code.

laravel-js-localization

Build Status Scrutinizer Code Quality Code Coverage Total Downloads

Simple, ease-to-use and flexible package for the Laravel web framework. Allows you to use localized messages of the Laravel webapp (see resources/lang directory) in your Javascript code. You may easily configure which messages you need to export.

⚠️ Looking for a new maintainer. Please contact me if you are interested.

Branches

Laravel Branch
8 laravel-8
7 laravel-7
6 laravel-6
5.8 laravel-5.8
5.0 - 5.7 laravel-5 (end of life)

Installation

Add the following line to the require section of your Laravel webapp's composer.json file:

    "require": {
        "andywer/js-localization": "dev-laravel-6"      // see table above
    }

Run composer update to install the package.

Finally add the following line to the providers array of your app/config/app.php file:

    'providers' => [
        /* ... */
        JsLocalization\JsLocalizationServiceProvider::class
    ]

Configuration

Run php artisan vendor:publish first. This command copies the package's default configuration to config/js-localization.php.

You may now edit this file to define the messages you need in your Javascript code. Just edit the messages array in the config file.

Example (exports all reminder messages):

<?php

return [
    // Set the locales you use
    'locales' => ['en'],

    // Set the keys of the messages you want to use in javascript
    'messages' => [
        'passwords' => [
            'password', 'user', 'token'
        ]
    ],

    /*
     * in short:
     * 'messages' => ['passwords']
     *
     *
     * you could also use:
     *
     * 'messages' => [
     *     'passwords.password',
     *     'passwords.user',
     *     'passwords.token'
     * ]
     */
     
    // Set the keys of config properties you want to use in javascript.
    // Caution: Do not expose any configuration values that should be kept privately!
    'config' => [
        'app.debug'
    ],
     
    // Disables the config cache if set to true, so you don't have to run `php artisan js-localization:refresh`
    // each time you change configuration files.
    // Attention: Should not be used in production mode due to decreased performance.
    'disable_config_cache' => false,

    // Split up the exported messages.js file into separate files for each locale.
    // This is to ensue faster loading times so one doesn't have to load translations for _all_ languages.
    'split_export_files' => true,
];

Important:

The messages configuration will be cached when the JsLocalizationController is used for the first time. After changing the messages configuration you will need to call php artisan js-localization:refresh to refresh that cache. That also affects the config properties you export to javascript, since they are cached, too.

Usage

The translation resources for JavaScript can either be served by your Laravel app at run-time or they can be pre-generated as static JavaScript files, allowing you to serve them straight from your web server or CDN or to be included in your build process.

Run-time generation

You just need to add the necessary <script> tags to your layout. Here is an example blade view:

@include('js-localization::head')
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Test view</title>
        @yield('js-localization.head')
    </head>
    <body>
        <p>
            Here comes a translated message:
            <script type="text/javascript">
                document.write( Lang.get('reminder.user') );
            </script>
        </p>
    </body>
</html>

Remember it's best to not put the @yield('js-localization.head') in the <head> as it contains the <script> tag shipping the frontend part of this package. It's best practice to put it at the end of the <body>, but before other <script> tags. The example above simply includes it in the head, since it's the simplest form to use it.

Static generation

For increased performance it is possible to generate static JavaScript files with all of your generated strings. These files can either be served directly as static files, or included as a part of your frontend asset build process.

To specify the output directory for the assets, just set the $storage_path string in your config/js-localization.php file accordingly (see Configuration).

    /*
    |--------------------------------------------------------------------------
    | Define the target to save the exported messages to
    |--------------------------------------------------------------------------
    |
    | Directory for storing the static files generated when using file storage.
    |
    */

    'storage_path' => public_path('vendor/js-localization/'),

The files can then be generated using the artisan command:

php artisan js-localization:export

This will generate two files in your target directory:

  • messages.js contains your translation strings
  • config.js contains your exported config values

If you want to automatically split up the messages.js file into separate .js files for each locale, you can set the following to true in your config/js-localization.php config file:

    'split_export_files' => true,

This will in turn also generate the following file(s) in your target directory:

  • lang-{locale}.js contains one language's translation strings, if the split_export_files config option is set to true

Remember that the files needs to be regenerated using php artisan js-localization:export every time any translation strings are edited, added or removed.

Features

You may use Lang.get(), Lang.has(), Lang.choice(), Lang.locale() and trans() (alias for Lang.get()) in your Javascript code. They work just like Laravel's Lang facade. Additionally, you are able to pass configuration properties to your Javascript code as well. There is Config.get() in Javascript, too. Configure which config properties to pass to the client using the config field in config/js-localization.php. Attention: Do not export any security-critical properties like DB credentials or similar, since they would be visible to anyone using your application!

Variables in messages are supported. For instance: "This is my test string for :name.".

Pluralization is also supported, but does not care about the locale. It only uses the English pluralization rule ("singular text|plural text"). More complex pluralization quantifiers are not yet supported.

Service providers

Assume you are developing a laravel package that depends on this javascript localization features and you want to configure which messages of your package have to be visible to the JS code.

Fortunately that's pretty easy. Just listen to the JsLocalization.registerMessages event and use the JsLocalization\Facades\JsLocalizationHelper::addMessagesToExport() method. Like so:

<?php

use Illuminate\Support\ServiceProvider;
use JsLocalization\Facades\JsLocalizationHelper;

class MyServiceProvider extends ServiceProvider
{
    /* ... */

    public function register()
    {
        Event::listen('JsLocalization.registerMessages', function()
        {
            JsLocalizationHelper::addMessagesToExport([
                // list the keys of the messages here, similar
                // to the 'messages' array in the config file
            ]);
        });
    }

    /* ... */
}

License

This software is released under the MIT license. See license.

More Repositories

1

webpack-blocks

πŸ“¦ Configure webpack using functional feature blocks.
JavaScript
2,979
star
2

threads.js

🧡 Make web workers & worker threads as simple as a function call.
TypeScript
2,942
star
3

leakage

πŸ› Memory leak testing for node.
JavaScript
1,583
star
4

pg-listen

πŸ“‘ PostgreSQL LISTEN & NOTIFY for node.js that finally works.
TypeScript
540
star
5

typed-emitter

πŸ”© Type-safe event emitter interface for TypeScript
JavaScript
250
star
6

use-inline-memo

βš›οΈ React hook for memoizing values inline anywhere in a component
TypeScript
163
star
7

postguard

πŸ› Statically validate Postgres SQL queries in JS / TS code and derive schemas.
TypeScript
161
star
8

squid

πŸ¦‘ Provides SQL tagged template strings and schema definition functions.
TypeScript
124
star
9

ava-ts

πŸš€ Fork of the AVA test runner with native typescript support
JavaScript
116
star
10

postcss-debug

Debug your postcss workflow with ease! Creates snapshots of your CSS files before/after each postcss plugin is run.
JavaScript
94
star
11

react-usestyles

πŸ– Style components using React hooks. Abstracts the styling library away.
JavaScript
87
star
12

postcss-theme

PostCSS plugin to enable versatile theming.
JavaScript
87
star
13

react-stateful-fn

βš› Stateful functional components for React.
JavaScript
57
star
14

puppet-run

πŸ€– Run anything JavaScript in a headless Chrome from your command line
TypeScript
53
star
15

threadpool-js

Javascript thread pool implementation using web workers.
JavaScript
47
star
16

jquery-dim-background

jQuery plugin to dim the current page except for some user-defined top elements.
JavaScript
43
star
17

observable-fns

πŸ•΅οΈβ€β™€οΈ Light-weight observable implementation and functional utilities in TypeScript
TypeScript
41
star
18

npm-launch

πŸš€ Minimalistic task runner on steroids!
JavaScript
39
star
19

drag-mock

Trigger HTML5 drag & drop events for testing
JavaScript
35
star
20

gear

πŸ›  Experimental tool to bootstrap typed JavaScript code.
JavaScript
33
star
21

proposal-double-colon-types

πŸ€“ JS / Flow syntax proposal. Types Γ  la Hindley-Milner.
20
star
22

http-event-stream

πŸ“‘ Modern spec-compliant Server Sent Events stream implementation.
TypeScript
19
star
23

ts

βš™οΈ The CLI that TypeScript deserves.
TypeScript
18
star
24

key-store

πŸ” Isomorphic encrypted key store written in TypeScript.
TypeScript
17
star
25

plow

πŸ‘¨β€πŸŒΎ Postgres migrations and seeding made easy
TypeScript
14
star
26

isomorphic-crypto

πŸ”’ Isomorphic crypto package for node and the browser.
JavaScript
12
star
27

type-reflect

☝️ TypeScript plugin providing access to type information at runtime
TypeScript
11
star
28

srv

πŸ“‘ Functional node server. Composable routing. Take a request, return a response.
TypeScript
9
star
29

rungpt

GPT client with local plugin framework, built by GPT-4
TypeScript
9
star
30

php-easygit

Manage Git repositories from within your PHP webapp. Commit, branch, clone, checkout, ...
PHP
7
star
31

zaster

πŸ’Έ Headless multi-blockchain wallet and SDK.
TypeScript
7
star
32

react-commandments

πŸ“– Thou shalt honor thy reactive code and keep it holy.
6
star
33

koa-router-index

Koa v2 middleware to create an index page for API servers.
JavaScript
5
star
34

gulp-elixir-modules

Elixir extension for handling frontend modules easily.
JavaScript
5
star
35

json-sql-import

Small PHP tool to import JSON data into database tables using transformation rules.
PHP
4
star
36

puppet-run-plugins

🧩 Plugins for puppet-run.
TypeScript
4
star
37

shutter-legacy

πŸ“Έ Visual snapshot testing with no effort.
TypeScript
3
star
38

deep-assert

πŸ” Better deep-equals comparison, supporting custom property assertions and pretty diffs.
TypeScript
3
star
39

ideabox

Place to collect techy ideas and get feedback.
1
star
40

bundle-decomposition-research

JavaScript
1
star
41

stellar-wallet

With the new Stellar wallet to the moon πŸš€
JavaScript
1
star