blok/laravel-javascript

Javascript add variables helper

1.1.1 2022-02-16 12:40 UTC

This package is auto-updated.

Last update: 2024-11-16 17:33:04 UTC


README

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.