JS Utilities

Lightpack’s Js utility provides a safe, expressive way to convert PHP data into JavaScript code for use in your views, scripts, or templates. It ensures proper escaping and supports all variable declaration types.


Overview


use Lightpack\Utils\Js;

$js = new Js();

Or you can use the js() utility function.

Encode PHP data as JavaScript

encode(mixed $data, bool $asObject = true): string

js()->encode(42); // 42
js()->encode('hello'); // "hello"
js()->encode(['a' => 1, 'b' => 2]); // {"a":1,"b":2}
js()->encode(['foo' => 'bar'], false); // JSON.parse('{...}')

Create JS variable declarations

Creates a JS variable declaration with the specified name and value.

js()->var('user', ['id' => 1]);   // var user = {"id":1};
js()->let('user', ['id' => 1]);   // let user = {"id":1};
js()->const('API_KEY', 'abc');    // const API_KEY = "abc";

Escaping & Safety