A Blade directive to export variables to JavaScript

Overview

A Blade directive to export variables to JavaScript

Latest Version on Packagist Software License GitHub Workflow Status Check & fix styling Total Downloads

This package contains a Blade directive to export values to JavaScript.

Here's an example of how it can be used:

@javascript('key', 'value')

The rendered view will output:

<script>window['key'] = 'value';</script>

So in your browser you now have access to a key variable:

console.log(key); //outputs "value"

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-blade-javascript

The package will automatically register itself.

Optionally the config file can be published with

php artisan vendor:publish --provider="Spatie\BladeJavaScript\BladeJavaScriptServiceProvider" --tag="config"

This is the contents of the published config file:

return [

    /**
     * All passed values will be present in this JavaScript namespace. Set this to an empty string
     * to use the window object.
     */
    'namespace' => '',
];

If you want to customize the generated <script> tag you can publish and override the used view.

php artisan vendor:publish --provider="Spatie\BladeJavaScript\BladeJavaScriptServiceProvider" --tag="views"

After this you can edit the published view resources/views/vendor/bladeJavaScript/index.blade.php. This is usefull to add the type or a CSP nonce.

Usage

With the package installed you can make use of a @javascript Blade directive.

@javascript('key', 'value')

The rendered view will output:

<script>key = 'value';</script>

You can also use a single argument:

@javascript(['key' => 'value'])

This will also output:

<script>key = 'value';</script>

When setting the namespace to eg js in the config file this will be the output:

<script>window['js'] = window['js'] || {};js['key'] = 'value';</script>

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

This repository contains some code from the laracasts/PHP-Vars-To-Js-Transformer package written by Jeffrey Way.

License

The MIT License (MIT). Please see License File for more information.

Comments
  • render numeric Strings as Strings

    render numeric Strings as Strings

    Some numeric sequences, such as social security numbers, phone numbers with no formatting, postal codes, etc. Should be rendered as strings, so they can keep leading zeroes for example and do not risk overflowing JavaScript Number.MAX_SAFE_INTEGER value.

    opened by rodrigopedra 5
  • Refactor the way the directive is registered

    Refactor the way the directive is registered

    I am not exactly sure why (package conflict perhaps?), but the blade directive suddenly stopped working for me in an existing project. It would render the @javascript as raw html from the blade file.

    After a bit of searching around, it seems Ziggy had a similar issue recently https://github.com/tightenco/ziggy/issues/115. The solution I propose below is the same as they just implemented for their package; and it seems to resolve the issue without breaking backwards compatibility

    Thoughts?

    opened by jkudish 4
  • Library generating invalid HTML output

    Library generating invalid HTML output

    Just started using this library and I noticed that the scripts are being added in an invalid manner. That's to say, when using this library the HTML output from Laravel now contains invalid HTML markup.

    For illustration purpose I've created a simple/empty template file. You can see this here:

    <script>window['key'] = 'value';</script>
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Test</title>
    </head>
    </html>
    

    When you attempt to validate this with an HTML validator it throws some errors. In total this creates 4 errors in the W3 HTML validator.

    • Start tag seen without seeing a doctype first. Expected .
    • Stray doctype.
    • Stray start tag html.
    • Cannot recover after last error. Any further errors will be ignored.
    opened by mallardduck 3
  • no CSP Support

    no CSP Support

    At the moment there is no CSP support by default - which is a bit strange cause you guys have also a laravel csp package.

    Refused to execute inline script because it violates the following Content Security Policy directive: "script-src ...". Either the 'unsafe-inline' keyword, a hash ('...'), or a nonce ('nonce-...') is required to enable inline execution.

    I don't want to allow inline scripts - so I have to set something on the script tag itself. Atm I've overriden the \Spatie\BladeJavaScript\Renderer class but this isn't optimal - there would be several ways to fix this.

    laravel-csp package related

    1. add the hash of the inline script to the policy https://github.com/spatie/laravel-csp/issues/33
    2. use the csp_nonce() function on the script

    general 3) use a blade file for the script tag that could be overriden

    which one do you like the most?

    opened by Gummibeer 3
  • Laravel 8.x Compatibility

    Laravel 8.x Compatibility

    This is an automated pull request from Shift to update your package code and dependencies to be compatible with Laravel 8.x.

    Before merging, you need to:

    • Checkout the l8-compatibility branch
    • Review all comments for additional changes
    • Thoroughly test your package

    If you do find an issue, please report it by commenting on this PR to help improve future automation.

    opened by laravel-shift 2
  • Append values to the existing namespace instead of override.

    Append values to the existing namespace instead of override.

    Hi! In some situations, to keep consistency, there is a need to use the same window namespace for custom solutions as we might use for assigning data via @javascript(). Current implementation of the module overrides data that have been declared before @javascript(). What do you think about appending data to the namespace if such already exists (and maybe even make it configurable?) instead of just clearing that?

    opened by nesskyy 1
  •  Improve rendering performance when rendering multiple variables

    Improve rendering performance when rendering multiple variables

    When passing an array of variables to the rendering the method getAllTransformers instantiates the transformers for each variable.

    This commit adds a $cachedTransformers to the Renderer so it instantiates the underlying transformers just once.

    opened by rodrigopedra 1
  • Render Strings with line breaks properly

    Render Strings with line breaks properly

    When the value has line breaks, such as user input from a textarea, the directive did not escape the line breaks properly leading to JavaScript errors.

    opened by rodrigopedra 1
  • Assigning Multiple Key Value Pairs

    Assigning Multiple Key Value Pairs

    Unless I'm missing it, I would like to suggest the feature to assign multiple key/value pairs at once to minimize the excess <script> tags.

    Something like this perhaps?

    @javascript(['key' => 'value', 'key2' => 'value2'])
    
    <script>window['key'] = 'value';window['key2'] = 'value2';</script>
    
    opened by grimmdude 1
  • Conflicts with Vue.js?

    Conflicts with Vue.js?

    Whenever I use the @javascript tag in my blade templates I get the following Vue.js error:

    - Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.
    

    Removing the tags from the template fixes the issue. Should I be using Vuex instead of this package? I very much prefer the simplicity of this package.

    opened by benjivm 1
  • [LaraPackagePort] Analyse for Laravel 5.5

    [LaraPackagePort] Analyse for Laravel 5.5

    This Pull-Requests help you to prepare your Package for Laravel 5.5. I've tested it automated and this was the PHPUnit Result: PHPUnit 6.3-dev by Sebastian Bergmann and contributors.

    Runtime: PHP 7.1.7 with Xdebug 2.5.5 Configuration: /Users/lukaskammerling/Code/OSS/spatieLaravelphp5.5/storage/spatie.laravel-blade-javascript/phpunit.xml.dist

    ............ 12 / 12 (100%)

    Time: 4.23 seconds, Memory: 14.00MB

    OK (12 tests, 13 assertions)

    Generating code coverage report in Clover XML format ... done

    Generating code coverage report in HTML format ... done

    Nice looks really good! There are no Errors so it might work in Laravel 5.5 without any adjustments

    opened by LKaemmerling 1
Releases(2.7.0)
Transform PHP data to JavaScript.

Transform PHP Vars to JavaScript Often, you'll find yourself in situations, where you want to pass some server-side string/array/collection/whatever t

Laracasts 2.2k Jan 1, 2023
Laravel Javascript Validation

Laravel Javascript Validation Laravel Javascript Validation package allows to reuse your Laravel Validation Rules, Messages, FormRequest and Validator

Proengsoft 991 Jan 4, 2023
Use your Laravel named routes in JavaScript

Ziggy – Use your Laravel routes in JavaScript Ziggy provides a JavaScript route() helper function that works like Laravel's, making it easy to use you

Tighten 3.1k Dec 28, 2022
Html Minifier adalah paket simpel untuk minify output Html, Css style, dan Javascript sebelum dirender ke browser untuk aplikasi Laravel anda.

Laravel Html Minifier Adalah Paket simpel untuk minify HTML, Css Style, dan Javascript sebelum dirender ke browser untuk aplikasi Laravel anda. Alat i

:D 16 Aug 17, 2022
Use your Laravel named routes in JavaScript

Ziggy – Use your Laravel routes in JavaScript Ziggy provides a JavaScript route() helper function that works like Laravel's, making it easy to use you

Tighten 3.1k Dec 28, 2022
A tidy conditional Blade directive for checking if something is in an array

A tidy conditional Blade directive for checking if something is in an array. This package provides a small @in directive that allows you to simplify i

Ryan Chandler 0 Oct 7, 2022
Preferences are configuration variables that are user-managed for which we cannot rely upon container parameters or environment variables.

Preferences Preferences are configuration variables that are meant to be user managed for which we cannot rely upon container parameters or environmen

Makina Corpus 1 Feb 7, 2022
Scripts-dev directive for composer

scriptsdev for Composer It's like require-dev, but for scripts Installation Just run composer require neronmoon/scriptsdev --dev Usage After installin

Vitaliy Krasnoperov 67 May 18, 2022
🎌 Laravel Localization Helper :: Easily add translation variables from Blade templates.

LocalizationHelper Package for convenient work with Laravel's localization features and fast language files generation. Take a look at contributing.md

Awes.io 36 Jul 18, 2022
Blade UI Kit is a set of renderless components to utilise in your Laravel Blade views

Blade UI Kit is a set of renderless components to utilise in your Laravel Blade views. In all essence, it's a collection of useful utilities, connecting the dots between different parts of the TALL stack. It was made for Blade, Laravel's powerful templating engine.

Blade UI Kit 1.2k Jan 5, 2023
Blade Snip allows you to use parts of a blade template multiple times. Basically partials, but inline.

Blade Snip Blade Snip allows you to use parts of a blade template multiple times. Basically partials, but inline: <div class="products"> @snip('pr

Jack Sleight 18 Dec 4, 2022
Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.

PHP dotenv Loads environment variables from .env to getenv(), $_ENV and $_SERVER automagically. Why .env? You should never store sensitive credentials

Vance Lucas 12.3k Jan 7, 2023
Symfony Dotenv parses .env files to make environment variables stored in them accessible via getenv(), $_ENV, or $_SERVER.

Dotenv Component Symfony Dotenv parses .env files to make environment variables stored in them accessible via $_SERVER or $_ENV. Getting Started $ com

Symfony 3.5k Jan 5, 2023
Handle PHP errors, dump variables, execute PHP code remotely in Google Chrome

PHP Console server library PHP Console allows you to handle PHP errors & exceptions, dump variables, execute PHP code remotely and many other things u

Sergey 1.4k Dec 25, 2022
Add variables to the payload of all jobs in a Laravel app

Inject extra info to the payloads of all jobs in a Laravel app This package makes it easy to inject things in every job. Imagine that you want to have

Spatie 62 Dec 9, 2022
Provides Twig template IDE autocomplete of Craft CMS & plugin variables

Autocomplete for Craft CMS 3.x Provides Twig template IDE autocompletion for Craft CMS and plugin/module variables and element types. Works with PhpSt

nystudio107 35 Dec 21, 2022
Search PHP source code for function & method calls, variables, and more from PHP.

Searching PHP source code made easy Search PHP source code for function & method calls, variable assignments, classes and more directly from PHP. Inst

Permafrost Software 22 Nov 24, 2022
A simple library to increase the power of your environment variables.

Environment A simple library (with all methods covered by php unit tests) to increase the power of your environment variables, contribute with this pr

João Paulo Cercal 56 Feb 8, 2022
Laravel 4.* and 5.* service providers to handle PHP errors, dump variables, execute PHP code remotely in Google Chrome

Laravel 4.* service provider for PHP Console See https://github.com/barbushin/php-console-laravel/releases/tag/1.2.1 Use "php-console/laravel-service-

Sergey 73 Jun 1, 2022
Routing - The Routing component maps an HTTP request to a set of configuration variables.

Routing Component The Routing component maps an HTTP request to a set of configuration variables. Getting Started $ composer require symfony/routing

Symfony 7.3k Jan 6, 2023