A Laravel package that provides a simple way to wrap JavaScript code stored in a file into a PHP class and inline it using a custom Blade directive. The PHP wrapper class also allows you to modify the script before inlining (for example, by replacing placeholders).
Allows ✨:
- passing variables from PHP to JavaScript,
- process / modify the script in a dedicated PHP class.
Additionally - has build in ready-to-use scripts (built using this package):
- ColorSchemeSwitchThreeStates - light / dark - color scheme switching script (+ view with icons)
- ColorSchemeSwitchTwoStates - light / dark / system - color scheme switching script (+ view with icons)
- LivewireNavAdapter - color scheme navigation state adapter for Livewire
- PHP 8.2 or newer
- Laravel 9.x or newer (wasn't tested with the older versions)
Install the package via Composer:
composer require zmyslny/laravel-inline-scriptsRegister a custom Blade directive for your JavaScript in your AppServiceProvider:
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
BladeInlineScripts::takeFiles(
resource_path('js/your-first-script.js'),
resource_path('js/your-second-script.js'),
...
)->registerAs('myInlineScripts');
}
}Use the custom Blade directive in your template to inline the scripts:
<html>
<head>
...
@myInlineScripts
</head>
<body>
...Done.
The package includes ready-to-use scripts. For example, to add a color scheme switcher:
use Zmyslny\LaravelInlineScripts\Ready\ColorSchemeSwitchTwoStates\InitScript;
use Zmyslny\LaravelInlineScripts\Ready\ColorSchemeSwitchTwoStates\SwitchScript;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
BladeInlineScripts::take(
new InitScript(),
new SwitchScript('d') // toggle dark & light modes with 'd' key
)->registerAs('colorScheme');
}
}Then use in your template:
@colorSchemeSee the Color Scheme Switch, Color Scheme Three States, and LivewireNavAdapter documentation for full details and customization options.
For more advanced script processing, create a PHP class that implements the RenderableScript interface to prepare or transform your JavaScript code. Use the abstract class FromFile to load scripts from files, or FromFileWithPlaceholders to include placeholder replacement (e.g., __VARIABLE__ → value).
Register your custom scripts using BladeInlineScripts::take(...).
For a complete working example with detailed setup instructions, see the Color Scheme Switch documentation.
This package is licensed under the MIT License.