GithubHelp home page GithubHelp logo

kg-bot / laravel-localization-to-vue Goto Github PK

View Code? Open in Web Editor NEW
238.0 238.0 36.0 131 KB

Make Laravel standard localization files available in format required by various JavaSript localization packages

License: MIT License

PHP 100.00%

laravel-localization-to-vue's Introduction

🌐Socials

LinkedIn

BuyMeACoffee

💻Tech Stack

PHP Laravel Vue.js TailwindCSS Python

📊GitHub Stats :



laravel-localization-to-vue's People

Contributors

ciamarro avatar esseremmerik avatar generation4 avatar jcalonso avatar kg-bot avatar laravel-shift avatar lsmith77 avatar ludo237 avatar martinp7r avatar maxacarvalho avatar meduzen avatar ollieread avatar patrick-de-caluwe avatar ridaamirini avatar robertgarrigos avatar stylecibot avatar tomhatzer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-localization-to-vue's Issues

Use Regex for HTTP routes as well

Not sure if this is a bug or if intended feature, but the regex setting (available in the laravel-localization.php config file) to exclude certain files is not applied when requesting the JSON over HTTP routes.

I have the following regex:

    'file_regexp' => [
        'php' => '/^((?!careers|mail_|about).)+\.php$/i',
        'json' => '/^.+\.json$/i',
    ],

The corresponding strings are excluded when I export the language files with the command line, but when I visit the route over HTTP the exclusion was not used. Did I miss anything?

Trans not defined in Vue method.s

Hello,
I have followed the instructions on setting up this package with laravel. I also installed Lang.js accordingly.
From my vue component, when I call the trans.get function in the template like this:

<p>{{ trans.get('words.share_post') }}</p>

it works fine but when I try calling trans.get in any of my component's methods I get the error below

app.js:4145 Uncaught ReferenceError: trans is not defined
    at VueComponent.onLinkCopied (app.js:4145)
    at app.js:81325
    at v.emit (app.js:51870)
    at c.value (app.js:51870)
    at c.value (app.js:51870)
    at c.value (app.js:51870)
    at c.value (app.js:51870)
    at new c (app.js:51870)
    at value (app.js:51870)
    at HTMLButtonElement.<anonymous> (app.js:51870)

Please how can I resolve this.
Thanks in advance

The package tries to connect to Redis during composer install -> artisan package:discover

The package tries to connect to Redis (or any other cache store) during the composer install command, specifically when the @php artisan package:discover runs.

That's a problem because when I'm building the app's Docker image, the cache store (in my case Redis) is not available yet.

Steps to reproduce the behavior:

  1. Init a Laravel app and configure the .env to work with Redis
  2. Install the package
  3. If it does not fail on the first run (composer require kg-bot/laravel-localization-to-vue), try to publish the config, apply the basic usage steps, and then run composer install again, but make sure the Redis server is not available.

Screenshots
CleanShot 2021-09-17 at 21 37 30@2x

Feature suggestion: Output Callback

Hello, i'm using your package together with https://kazupon.github.io/vue-i18n/
Here is the thing:
Laravel translation parameters look like ":parameter"
Vuei18n expects "{parameter}"

This is my solution:
Route::get('/lang/localization.js', function () { $translate = ExportLocalization::export()->toArray(); array_walk_recursive($translate, function (&$v, $k) { $v = preg_replace('/:(\w+)/', '{$1}', $v); }); return response()->json($translate); });
(applied a regex replace on every translated string)

It would be nice to have a built-in callback setting to customize the output

Unable to prepare route

I am getting an error:

Unable to prepare route [js/localization.js] for serialization. Uses Closure.

It's because you're using a Closure in the routes file: https://github.com/kg-bot/laravel-localization-to-vue/blob/master/src/routes.php

Instead you should do something like:

Route::get(config('laravel-localization.routes.prefix'), 'KgBot\LaravelLocalization\Facades\ExportLocalizations@exportToArray') ...

Then in Facades\ExportLocalizations.php add:

public static function exportToArray(){
    $strings = ExportLocalizations::export()->toArray();
    return response()->json($strings);
}

Not getting the data in vuejs component

I have did every thing as the documentation say,
when I log the lang object I get the data exported but when I use trans.get() or trans,has() always false.

Please help me

Laravel 9 Support

Is your feature request related to a problem? Please describe.
The current version of this package doesn't support laravel 9

[Feature request]: Export to JSON files

this feature would be great to have since it would allow users to have more options on what they would be able to do with the export... it also supports i18n-ally which is a vscode Extension

something like this would be a good format when exporting to json

php artisan export:messages --json

to those who stumble upon this Issue... here's how I generate json files

Artisan::command('lang-export:messages-json', function () {

    $languages = ExportLocalizations::export()->toArray();

    foreach ($languages as $language_key => $translations) {
        foreach ($translations as $translation_key => $translate) {
            // dd($translation_key, $translate);

            $filepath = config('laravel-localization.js.filepath', resource_path('assets/js'));
            $filepath = "$filepath/$language_key";
            $filename = "$translation_key.json";

            $adapter = new Local($filepath);
            $filesystem = new Filesystem($adapter);

            $contents = json_encode($translate, JSON_PRETTY_PRINT);


            if ($filesystem->has($filename)) {
                $filesystem->delete($filename);
                $filesystem->write($filename, $contents);
            } else {
                $filesystem->write($filename, $contents);
            }
        }
    }

    $this->info('Messages exported to JSON files, you can find them at '.$filepath);

    return 0;


})->purpose('Export the languages to json');

if you have a directory structure like the one below,

en/passwords.php
en/auth.php
en/pagination.php
en/validation.php
ja/passwords.php
ja/auth.php
ja/pagination.php
ja/validation.php

this code will generate this output

en/passwords.json
en/auth.json
en/pagination.json
en/validation.json
ja/passwords.json
ja/auth.json
ja/pagination.json
ja/validation.json

Originally posted by @yob-yob in #70 (comment)

trans not define

H I install this library, and the manually install lang.js using NPM. Messages is loaded using View Composer.

Blade

<!-- laravel-localization-to-vue JS -->
        <script>

            window.default_locale = "{{ config('app.lang') }}";
            window.fallback_locale = "{{ config('app.fallback_locale') }}";
            window.messages = @json($messages);

        </script>

Then I put this in my Laravel app.js

import Lang from 'lang.js';

const default_locale = window.default_locale;
const fallback_locale = window.fallback_locale;
const messages = window.messages;

Vue.prototype.trans = new Lang( { messages, locale: default_locale, fallback: fallback_locale } );

And try to console.log in my Vue component

<script>

    export default {
        mounted() {
           console.log(trans.get('auth.failed'));
        },
    }

</script>

However I get this error

[Vue warn]: Error in mounted hook: "ReferenceError: trans is not defined"

If I try this

<script>

    export default {
        mounted() {
           console.log(this.trans.get('auth.failed'));
        },
    }

</script>

Will output the lang key, but not the actual value

image

Quick check on html, the language was loaded

image

Loading lang-files base on loaded files, instead of using paths list in config.

This package is using the list config('laravel-localization.paths.lang_dirs') to decide which language files must be read and parsed.
Is the a reason behind this approach ??

In my opinion there's a better way, using the list of files that Laravel-Translation has already loaded (including those files loaded via service providers of packages).

Advantages of my suggested way :

  • Loading files in a more dynamic way, instead of usign a config file.
  • Loading those files that package providers loads.
  • Understanding the namespaces that defined by $this->loadTranslationsFrom(..); in service providers

The reason why I submit this Feature Request before any PR, is that I'm not sure if there was any other idea behind the current approach.

By the way, I have a commit ready for it, if such change is useful, tell me to submit a PR for it.

@kg-bot 🙏🏻

Your v1.6.2 introduces a breaking change

You've added a constructor to:

KgBot\LaravelLocalization\Classes\ ExportLocalizations

The constructor:

    public function __construct($phpRegex, $jsonRegex)
    {
        $this->phpRegex = $phpRegex;
        $this->jsonRegex = $jsonRegex;
    }

Is new and has non-typed and non-nullable arguments that cause errors. In my local version, I have overridden this class to allow for something that I need in the codebase. I did this with v1.6.1 and upon running composer update it all breaks because the regexes have vanished, the constructor has appeared and the container cannot find the 'dependencies'.

Are you not following semantic versioning?

Add Laravel 7 support

Since Laravel 6 nothing that could brake package has changed, so it's just about adding |^7 the version in composer.json.

Localization JSON format isn't working fine with Lang.js

I tried to use the Lang.js module like u showed in the example, but i am bit confused about JSON format and getting the translation by key.

Exported format:

{
  'en':{
     'greetings': {
        'hi': 'Test'
      }
    },
   'it': {
      'greetings': {
         'hi': 'Salve'
    }
  }
}

Lang.js required format:

{
 'en.greetings': {
   'hi': 'Hi',
   'hello': 'Hello'
  },
 'it.greetings': {
     'hi': 'Salve'
   }
}

Vue part

// With first format
trans.get('greetings.hi'); // > "greetings.hi"

// With second format
trans.get('greetings.hi'); // > "Hi"

trans is not defined in vue extended component

I am using vue-multiselect component and to translate their placeholders and labels globally, I am extending the component but in props, I cannot use trans.get. Error - trans is not defined. Do I need to import something here? In page components, I could use trans inside </template section. Not sure about props though

import Multiselect from 'vue-multiselect';
export default {
    extends: Multiselect,
    props: {
        selectLabel: {
            type: String,
            default: trans.get('__JSON__.Press enter to select')
        },
        selectedLabel: {
            type: String,
            default: trans.get('__JSON__.Selected')
        },
        deselectLabel: {
            type: String,
            default: trans.get('__JSON__.Press enter to remove')
        },
        placeholder: {
            type: String,
            default: trans.get('__JSON__.Select option')
        }
    }
}

Problem reading default lang folder path

In v1.5.5 there is a problem reading default resources/lang folder.
To fix this I needed to change laravel-localization.php on line 92
from : ['resources/lang'], to : [resource_path('lang')],
As this returns relative path and first one couldn't find lang folder.
Please fix that

Composer require: Invalid argument supplied for foreach()

Describe the bug
When I try installing this package using the command
composer require kg-bot/laravel-localization-to-vue, I get the error message shown below

 ErrorException 

  Invalid argument supplied for foreach()

  at vendor/kg-bot/laravel-localization-to-vue/src/Classes/ExportLocalizations.php:67
    63| 
    64|             return $this;
    65|         }
    66| 
    67|         foreach (config('laravel-localization.paths.lang_dirs') as $dir) {
    68|             try {
    69| 
    70|                 // Collect language files and build array with translations
    71|                 $files = $this->findLanguageFiles($dir);


  4   [internal]:0
      KgBot\LaravelLocalization\Console\Commands\ExportMessages::__construct()

I am using laravel 7 and php 7.3,

Output Error after Exporting messages

Hi, I have been using this package for while a now, every time I update the language JSON file in resources\lang, the function trans.get(__JSON__.title) for example, does not outputs the string from the messages file in resources\assets\js, even if it's exported right, still won't show. However, in the first time when included this package is worked just great and just after exporting, it sometimes shows the locale string and sometimes it not. I have tried to php artisan config:cache after every php artisan export:messages and also didn't fix the problem. I hope there is a solution for this error.

Malformed UTF-8 characters, possibly incorrectly encoded

Describe the bug
When i try to access the link: http://localhost/js/localization.js
this error is thrown. Malformed UTF-8 characters, possibly incorrectly encoded

To Reproduce
Steps to reproduce the behavior:

  1. Go to 'http://localhost/js/localization.js '

Expected behavior
Should return at least a javascript file with all the translations

Screenshots
Screen Shot 2022-05-22 at 18 23 37

Desktop (please complete the following information):

  • OS: MacOS (But im using laravel sail, so it is basically ubuntu)
  • Browser Chrome
  • Version 101.0.4951.64 (Official Build) (x86_64)

Additional context
Im using laravel 9.13.0

need to change app.lang to app.locate

for new laravel version in docs

// Inside blade view
<script>
    window.default_locale = "{{ config('app.lang') }}";
    window.fallback_locale = "{{ config('app.fallback_locale') }}";
    window.messages = @json($messages);
</script>

Should change

window.default_locale = "{{ config('app.locale') }}";

ECMAScript 6 standard JavaScript module

Hi

I'm struggling to import the module exported via the artisan command.
The resulting file is something like

export default messages = {"en":{"auth":{"failed":"...

When I'm trying to use it

import messages from './ll_messages';
console.log(messages);

Uncaught ReferenceError: messages is not defined
    at eval (ll_messages.js?f4b1:1)

If I simplify the exported JS as

export default {"en":{"auth":{"failed":"These credent...

Then I can use the imported data.

I'm I misunderstood something here? Can you help me out please, how am I supposed to use this?

Custom interpolation (ex: for i18n)

Hi,

Great package!

I hope it is not a feature request, cause hope I just don't know how to do that with your package :)

So is it possible to generate laravel translations string:

Confirm delete :name :type?,

To:

Confirm delete {name} {type}?,

If not, than it is feature request :)

Trans.get not working

Hello,

I think there is an error. Your code forms all language files as a json string. With locale attribute and translate files and values.
The lang.js needs the data as a json object as well but locale is part of the attribute e.g. "en.greetings"
var lang = new Lang({ messages: { 'en.greetings': { 'hi': 'Hi', 'hello': 'Hello' }, 'it.greetings': { 'hi': 'Salve' } } });

PHP 7.0 Support

I have tried to install this package on Laravel 5.5 but i get following error

Could not find package kg-bot/laravel-localization-to-vue at any version matching your PHP version 7.0.32.0

It would be nice when u support Laravel 5.5 and PHP 7.0.

Or is there any reason why PHP 7.1 is required ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.