Looking to hire Laravel developers? Try LaraJobs

laravel-javascript maintained by blok

Description
Javascript add variables helper
Author
Last update
2022/02/16 13:40 (dev-master)
License
Links
Downloads
1 198

Comments
comments powered by Disqus

Set PHP variables to a JavaScript global helper

Scrutinizer Code Quality Build Status Packagist Packagist

Installation

Begin by installing this package through Composer.

composer require blok/laravel-javascript --prefer-dist
{
    "require": {
        "blok/laravel-javascript": "~1.1"
    }
}

Laravel Users

If you are a Laravel user, there is a service provider you can make use of to automatically prepare the bindings and such.


// config/app.php

'providers' => [
    '...',
    Blok\JavaScript\JavaScriptServiceProvider::class,
];

When this provider is booted, you'll gain access to a helpful JavaScript facade, which you may use in your controllers.

public function index()
{   
    javascript('foo', 'bar');
    // or
    javascript()->add('foo', 'bar');
    // area aliases for
    javascript()->set('foo', 'bar');
 
 
    javascript([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29,
    ]);
    // or
    javascript()->add([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29,
    ]);
    // area aliases for
    javascript()->set([
        'foo' => 'bar',
        'user' => User::first(),
        'age' => 29,
    ]);
    
    
    javascript()->namespace('_labels')->set(Label::all());
    // is an alias of
    javascript()->setNamepace('_labels')->set(Label::all());
}

In Laravel 5, of course add use JavaScript; to the top of your controller.

Then, you need to render the JavaScript. For example :

<body>
    <h1>My Page</h1>
    
    @javascript() // render default '__app' namespace in window.__app global
    // is the same as 
    {!! javascript()->render() !!}
    // alternatively
    <script>{!! javascript()->render(null, [], false) !!}</script>
    
    @javascript('_labels') // render '_labels' namespace in window._labels global
    // is the same as
    {!! javascript()->render('_labels') !!}
    // alternatively
    <script>{!! javascript()->render('_labels', [], false) !!}</script>
</body>

Versioning

Versioned using SemVer.

Contribution

Please raise an issue if you find any. Pull requests are welcome!

Author

License

This project is licensed under the GPL License - see the LICENSE file for details.